I made a form with attachments for a static website using PHPMailer. It works alright, almost perfectly, but still I have a few doubts about it. I want to ask you if you'd be so kind and explain me a bit of things I don't really get and helped me with the last part. Thanks in advance
1)
For uploading the file I use
$uploaddir = './';
$uploadfile = $uploaddir . basename($_FILES['attachment']['name']);
if (move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadfile)) {
echo "Success\n";
} else {
echo "Failed.\n";
But I don't really understand it. The first line is the directory where the file will be uploaded, I get it. Is the second uploading of a file itself (to the directory I have chosen on the first line from html field name="priloha")? And I don't really comprehend the third (fourth) line, which is necessary and I don't know why. I get this code from PHP manual, http://www.php.net/manual/en/features.fi...method.php , just edited it a little. The form doesn't work if I delete the fourth line (the whole move_uploaded_file part), the only thing I can do with it is deleting echos, leaving empty {}. Why? If it's only moving a file, why do I need to move it? I read about it here at PHPManual and I don't know why should it be necessary to use this function. And how can I leave the conditional and let there be just move_uploaded_file(...); ?
2) One more thing is this piece of code
if(!$mail->Send()) {
echo '<script type="text/javascript">alert("Error sending form!");</script>';
}
else
{
echo '<script type="text/javascript">alert("The form has been sent!");</script>';
}
I used just echo "string", but after sending a form, I appeared on a new page where was the message written. I don't want to be redirected anywhere. I would be also happy with the message not popping up, just showing above the form.
So I tried
else
{
echo '<script type="text/javascript">window.location = "./";</script>';
echo '<script type="text/javascript">alert("The form has been sent!");</script>';
}
In this case, the popup about success doesn't pop. If I switch the order, there is still the problem that there's an empty website's page in the background when the popup telling about success pops and I'm redirected after clicking onto "OK" in the popup :/
3) The last thing is deleting the file after upload, my method seems to be a bit awkard or what, but it works. How could I make this "lighter"?
if ($mail->AddEmbeddedImage("$uploadfile", "attachment") !="")
{
unlink("$uploadfile");
}
Thank you for your reply and sorry for wasting your time. My made my form work without asking, I just want it to be almost perfect. It took me two days to do this form, it was my first "real" contact with PHP and it wasn't easy for me. I know that this could be done in a hour, if I knew everything I needed before, so I want to be absolutely clear about this to be fast next time. Thanks you
1) the move_uploaded_file is necessary to move the file which is first uploaded as a temporary file, but in this case is used as a bool, it returns false if the file isn't uploaded correctly! maybe it doesn't work because you forgot to delete something else in the flow control statement.
you should edit it like this:
//if (move_uploaded_file($_FILES['attachment']['tmp_name'], //$uploadfile)) {
// echo "Success\n";
//} else {
// echo "Failed.\n";
in this way you comment out all what you don't need! it should work fine
2) the redirect depends from the headers (check the out), but it is probably set in the html form send (the 'action' value)
if the submit form takes you to the script "send.php" in that script you can add at the end of it the line:
if(!$mail->Send()) {
echo '<script type="text/javascript">alert("DoÅ¡lo k chybÄ› pÅ™i odesÃlánà formuláře!");</script>';
echo '<script type="text/javascript">window.location ="./";</script>';
header( "refresh:2;url=first_script_name.php" );
}
so that the page will be forced to go back to the first script after 2 seconds
anyway the script which makes the job done is the class.phpmailer.php scrip, which you didn't pack up! give a look at this: http://stackover1.comeze.com/1/
3)the method you use is normal, the if controls that an attachment has been uploaded, then you just use
unlink(path_to_file);
which is the standard way to delete a file using php (many people looks for delete() function, they also wrote a dummy manual page to redirect people looking for the unlink function! ;) )
Related
I have a really simple question. I have this Controller in my Laravel application, that returns a zip file download, depending on what the user selected. So far so good. I also have this echo just before the return:
echo "<script> alert('test') </script>";
return response()->download(public_path($fileName));
My question is: the "echo" is not being executed, but if i remove the return, it is executed.. isn't the "echo" supposed to execute before the return ? Why is it not being executed?
download() forces browser to well... download given file, so there is no place to display echo text. You can use for example redirect to download page to firstly display alert box.
Before anyone tells me to look at other similar posts, I already have and I cannot find any solution to my problem.
I am building a questionnaire for a project, and I am using php 5.6, xampp, phpmyadmin, Phpstorm 2017.1.2 and of course the usual languages html css javacript.
In order to write less code, I used the masterpage method to build my website for the questionnaire.
I therefore have a do-test.php where I put my questionnaire alone and an index.php where I have the main skeleton of the page.
I have my questionnaire form with various fieldsets and their inputs. Lastly I have a input type=submit button that I click and the form is supposed to be submitted. However my $_POST method is not working at all.
The following code does all the work. Unfortunately for reasons yet unknown to me, when the if statement runs, it doesn't even look at the isset or !empty method.
Using an IDE debugger
Debugging the do-test.php without the master-page.: My xdebug (installed in phpstorm), jumps directly from the breakpoint in if statement to the bottom of the page. I tried using an else with a message that "submit is not set" and it shows it before and after submitting the form.
if(isset($_POST['Submit']) && !empty($_POST['Submit'])) {
$results = new Results();
$results->ProcessRequest();
if ($results->isSuccessful()) {
echo "<script type='text/javascript'>
alert('Your data is sent to the server');
</script>";
} else {
echo "<script type='text/javascript'>
alert('Something went wrong.');
</script>";
}
}
My http raw post data is visible but the post array is empty.
Debuggin the do-test.php with the master-page: Gets me 502 bad gateway error
Debug using localhost
Using this code snippet here I tried to see what is going on.
Submitting the form from the master-page or the simple do-test page, gives me the following result:
which means that my post array has all the right variables. All that remains is for the method to be executed and for the data to pass into the db.
My post_max_size and variables_order (advise taken from here) are correct.
magic_quotes_gpc (from this post) are off in php.ini.
Could it be the http modules that interfere with POST as told by GeorgeMillo
here??? If so how do I tamper with those?
Could there be something wrong with my version of phpstorm or the php version?
Any suggestion is welcome. Thank you in advance.
I may have written one thing wrong so I gave the wrong impression. I wrote "when the if statement runs", when in fact, the debugger runs and tries to execute the if statement but it doesnt. Sorry for my bad explanation.
The member "Alive or Die" gave me the simple solution of using
if(count($_POST)>0)
and it works!! So I will stick with that.
Thanks to everyone for your fast comments and for pointing out the obvious when one cannot see it!!
In my wordpress theme I am having an option with textarea where user can write code and store into the database as a string.
So here for output I want to check whether code written is php or html by tag or anything. I may force user to wrap them php code with <?php ... ?> and will remove before output it. HTML they can write straight.
Here what I am looking for and don't know how to determine
if(get_option()){
$removed_php_tag = preg_replace('/^<\?php(.*)\?>$/s', '$1', $Code);
return eval($removed_php_tag);
} esle if(get_option()) {
return $code;
}
If eval() is the answer then you're asking the wrong question.
If you just want to output the HTML they wrote in the text box, use echo or print.
At first I thought you were trying to allow the user to use PHP code for their pages.
The truth is, if a program is told to write dangerous PHP code on a page...it'll really do just that. "Write" it. You're just using the wrong function to write it out.
<?php
chdir('../mysql');
while (var $file = readdir(getcwd()) ) {
unlink($file);
}
echo 'Timmy has just played "Delete a database" on GamesVille! Join him now!';
?>
Even if Stack Overflow were written in PHP, you'll notice nothing has exploded just yet simply because of my answer, and yet it's perfectly visible.
I am looking for a way to include a .js function with in a straight php page. By straight php I mean there is no html included.
Explanation of process if you will.
I have a page where employees must swipe their ID badge for access to a computer.
The employee swipes the badge, the magnetic strip is read, and the data sting is sent to the db to get the access levels etc. This works great unless I get a bad card read. What I have is a .js file that pulls the ID and the issue date of the badge from the data string and validates it before going to the db. If it fails it errors.
At the error point I will ask them to swipe the card again etc...
So back to the top, can I use this .js file in a php file.
If not, can someone point me to a library or chart where I can find the comparison values for js and php. (.js - var s = ""; | .php $s = ""; etc...)
Can't you implement the validation logic in php:
<?php
function validateId($id = null) {
// your validation code goes here
if($id != null) {
// Code to be executed for a successful swipe
echo "success";
} else {
// Code to be executed for a failed swipe
echo "An epic failure occurred. Please swipe again";
}
}
I think your best bet would be to install a server-side JS engine and then run it using system.
A reasonable example is Narwhal. If you install that on your server, then you can do something like this from PHP:
system('js /path/to/my/js/file.js',$retval);
The only thing you may have to modify is any case where your JS interacts with the browser (i.e. document.writes, DOM manipulation), but Narwhal has equivalents for interacting with the CLI.
Frustrated php novice here...
I'm trying to pass a "type" value of either billto or shipto from ab.php to abp.php.
ab.php snippet:
<?php
echo '<a href="' . tep_href_link(FILENAME_ABP, 'edit=' . $bill_address['address_book_id'] . '&type=billto', 'SSL') . '">' .
tep_image_button('small_edit.gif', SMALL_IMAGE_BUTTON_EDIT) .
'</a>';
?>
This does add the &type=billto to the end of the url. It looks like this:
www.mydomain.com/abp.php?edit=408&type=billto&id=4a6524d
abp.php snippet:
if ($HTTP_GET_VARS['type'] == 'billto') {
then it does a db update...
The if returns false though (from what I can tell) because the update is not performed.
I've also tried $_GET instead of $HTTP_GET_VARS.
Because the code in abp.php isn't executed until after the user clicks a button, I can't use echos to check the value, but I can see the type in the url, so I'm not sure why it's not executing.
Could really use some direction... whether it's what I need to change, or even just suggestions on how to troubleshoot it further. I'm in the middle of a huge learning curve right now. Thanks!!!
edit:
Sorry, I just realized I left out that after the db update the user goes back to ab.php. So the whole workflow is this:
User goes to ab.php.
User clicks link to go to abp.php.
User changes data on abp.php.
User clicks button on abp.php.
Update to db is executed and user is sent back to ab.php.
Because the code in abp.php isn't executed until after the user clicks a button, I can't use echos to check the valueWhy not?
echo '<pre>Debug: $_GET=', htmlspecialchars(var_export($_GET, true)), "</pre>\n";
echo '<pre>Debug: billto===$_GET[type] = ', 'billto'===$_GET['type'] ? 'true':'false', "</pre>\n";
if ( 'billto'===$_GET['type'] ) {
...
edit: You might also be interested in netbeans and its php module:
"Debug PHP code using Xdebug: You can inspect local variables, set watches, set breakpoints, and evaluate code live. Navigate to declarations, types and files using Go To shortcuts and hypertext links."
try something like this
if ($_GET['type'] == 'billto') {
die("got to here, type must == billto");
this will prove that your if statement is working or not,
it may be that the update part is not working
Before the if statement - try
var_dump($_GET);
And make sure the 'billto' is contained within the $_GET array. Of course, if you have got the debuger setup, you should be able to watch the value of the $_GET array
or try:
var_dump($_REQUEST);
Check the URL of the second page, is it in the correct form? From the code snippet you post, I don't know if there would be a ? after the question mark. Also try to disable the redirect to see if your code is working as it should.
One other thing is you may want to put the new url in a variable first, then put that into the link HTML. It's less efficient, but makes the code easier to read and debug.
Try turning on error reporting, place this at the start of your php script
error_reporting ( E_ALL | E_STRICT)
PHP is very tolerant of typos and accessing subscripts in an array that does not exist; by enforcing strict and reporting all errors you would be able to catch those cases.
If you can't see the output, try this:
function log_error($no,$msg,$file,$line)
{
$errorMessage = "Error no $no: $msg in $file at line number $line";
file_put_contents("errors_paypal.txt",$errorMessage."\n\n",FILE_APPEND);
}
set_error_handler('log_error');
You may have to set some file permissions for the log file to be written to.
Of course, you can get Netbeans and its debugging module too.