PHP Not Displaying How I'd Expect - php

EDIT: I've found the source of the problem. It was the webserver, but it was the way that the webserver was processing my requests via my index page. In other words, a foolish mistake on my part. I only discovered this because of the comments in this thread, however, so thank you.
I've recently started taking a PHP class for school, however I can't seem to get any of my PHP to work. We are supposed to upload our projects to a provided website via FTP, so PHP and all necessary pieces should already be setup on the website. For my first project, I was basically instructed to copy/paste a piece from the textbook and upload it. Even this did not work, coming back with a "No input file specified" error. The code for that was:
<?php
//Get current time in a readable format
$currentTime = date( "M j, Y g:i:s a" );
//Display greeting and time
echo "Hello, world! The current time is $currentTime";
?>
I assumed it was something that would fix itself with time and moved on. Just now, I was working on the next exercise, it stated to create a file with the following code:
<?php
$radius = 4;
$diameter = $radius * 2;
$circumference = M_PI * $diameter;
$area = M_PI * pow( $radius, 2 );
echo "This circle has... <br /> ";
echo "A radius of " . $radius . " <br /> ";
echo "A diameter of " . $diameter . " <br /> ";
echo "A circumference of " . $circumference . " <br /> ";
echo "An area of " . $area . " <br /> ";
?>
However when I tried opening this to check and see if it worked, it returned the following:
"; echo "A radius of " . $radius . "
"; echo "A diameter of " . $diameter . "
"; echo "A circumference of " . $circumference . "
"; echo "An area of " . $area . "
"; ? >
This result... doesn't even make sense to me. At all. Even if it was just pasting my lines as plain text they aren't formatted like that. I understand this is probably an entirely basic question to be asking but I'm just starting PHP and none of this makes sense. None of it is explained either.
EDIT: I've been asked for a bit more information, so here is what I can give.
For the first example, I uploaded it to the webserver via FileZilla and when I opened the webpage, the only text was an unformatted "No input file specified." When I hit "View Source Code", the source code also said simply "No input file specified", despite the fact that I definitely uploaded a .php file with code in it to the webserver.
For the second example, it is clear to me that I messed up, as I simply tried opening the file in Google Chrome, not associated with any webserver. I had no idea you couldn't do that, and honestly that seems fairly inefficient, but I guess it can't be helped.
There is yet a third example that I just uploaded to the server now. An actual exercise that is a part of the homework for the class. The file I uploaded had this exact code:
<html>
<body>
<?php
$x = 4;
$x = $x + 1;
$x += 1;
$x++;
echo $x;
?>
</body>
</html>
This file also returns "No input file specified."

Notice how you start getting input right after the first > in your code.
This is a sure sign that PHP isn't processing your file.
Did you name your file something.php? It needs that .php extension, or else custom configuration, or else it won't handle it.

Are others having the same problem? If the files are named *.php then perhaps the PHP module is not enabled on the web server or the web server is somehow otherwise configured incorrectly.

Related

What is wrong with my 'Save File' php code?

The question is simple but i will give some background information to hopefully make answering it easier.
So, I am working with the ELGG framework and taking information from a form and the text boxes in it in hopes to print that data to a simple text file.
Unfortunately, for some reason this has been giving me lots of trouble and I cannot seem to figure out why no matter where I look.
Code is as followed
<?php
error_reporting(E_ALL);
//Get the page
$title = get_input('title');
$body = get_input('body');
$date = date("l jS F Y h:i A");
//remove any possible bad text characters
$FileName = $title . ' ' . $date;
//print to file
//get filename and location to save
$folderName = '/Reports/' . $FileName . '.txt';
$ReportContent = "| " . $body . " |";
//write to the file
file_put_contents($folderName, $ReportContent, 0);
//error check to see if the file now exists
if (file_put_contents($folderName, $ReportContent)) {
system_message("Report Created (" . basename($folderName) . ")");
forward(REFERER);
} else {
register_error("Report (" . basename($folderName) . ") was not saved!");
forward(REFERER);
}
So what above SHOULD do is grab the text from the title and body box (which i can confirm it does from the title at least) and then save it under the /reports/ folder (full path for the plugin is Automated_script_view/reports/ if needed). Yet I will always get the register error, and I cannot seem to find why.
I believe it has to do with the declaration of the folder (/reports/), as if I take that part away, it passes and submits, although it doesn't seem to actually save anywhere.
Any and all advice would be very much appreciated!
The Function file_put_contents(file,data,mode,context) returns the number of character written into the file on success, or FALSE on failure. Note the following corrections and your script will work just fine:
1 Your File name has an 'illegal' character ":" coming from the $date part of the string you concatenate to form the filename.
2 Remove file_put_contents($folderName, $ReportContent, 0); Since the function returns an integer, simple use:
if( file_put_contents($folderName, $ReportContent) > 0 ){
//true
}else{
//false
}

How do you put a session like this into an array

I have the follow two files and I would like to transmit information between the two files using a session, but I am not getting the right results. Here are the files
index.php:
<?php
session_start();
for ($i=0; $i<=2; $i++) {
echo ("<p><a href='getpage.php?row=$item_title' target='_blank'>" . $item_title . "</a>");
echo ("<br>");
echo ($item_desc . "</p>");
$_SESSION['item_link'] = $item_link;
$_SESSION['item_title'] = $item_title;
}
and the getpage.php has the following
<?php
session_start();
if (isset($_SESSION['item_link']) && isset($_SESSION['item_title'])) {
$item_link = $_SESSION['item_link'];
$item_title = $_SESSION['item_title'];
header( "Location: $item_link" );
}
But I keep getting the last item_link when I click the link and run the getpage.php file by clicking the link from the index file. How do I put the session into an array so that I am not only getting the last value in session after you click the link?
This is a quick drive-by attempt at an answer, but you might try
$_SESSION['item_link'][] = $item_link;
$_SESSION['item_title'][] = $item_title;
Then your session variables will themselves be arrays.
I suspect your code is based on a misunderstanding on the underlying mechanics. Files are nothing but static assets, nothing but a bunch of zeroes and ones that do nothing but use disk space until you do something with them.
Just printing the name of a file:
echo ("<p><a href='getpage.php?row=$item_title' target='_blank'>" . $item_title . "</a>");
... will neither execute the file nor load it in memory or assign any resource of variable to it. It's just text. Variables defined in the for-each-file loop will not transmit to the files. The source code in the file will eventually run when the user clicks on the link.
Secondly, that's not how PHP sessions work anyway. Session data is not attached to a specific file, it's session-wide information.
You appear to be partially aware of URL parameters. That's the proper way to transmit information as long as it isn't sensitive or too long. If you pass $item_title in the URL:
echo ("<p><a href='getpage.php?row=$item_title' target='_blank'>"
... it'll be available right at $_GET['row']. There's no need to fiddle with sessions:
$_SESSION['item_link'] = $item_link; // What for?
Last but not least, when you inject text into a string that's aimed to be consumed by a computer (such as a URL or an HTML document) you need to ensure you don't break the data format. PHP provides the following built-in tools:
For URLs: rawurlencode()
For HTML: htmlspecialchars()
So your echo should look like this:
echo ("<p><a href='getpage.php?row=" . htmlspecialchars(rawurlencode($item_title)) . "' target='_blank'>"

Form to CSV and "Thanks" in new tab using POST

I'm trying to accept a form and write it to a CSV (invisible to the people submitting the form, but I can look at it as a compilation of everyone's entries on the server when I feel like it). Every time someone enters the form, it will become a new line on the CSV. To show that the people are actually submitting, a new tab will pop up with a little "thank you" like message and their submission so they can make sure it's theirs. Yes, I do have a JS form validation that works perfectly, but since that doesn't have a problem I left it out to save space.
Here is my current problem. In Firefox, I just get a blank new tab and nothing changes on my--blank--CSV, which is titled testForm.csv. In Chrome, a new tab opens that contains all the code on my php document, and my CSV stays blank.
Here's the snippet of my HTML:
<html>
<body>
<form name="Involved" method="post" action="postest.php" target="_blank" onsubmit="return validateForm();">
Name: <br><input type="text" name="name" title="Your full name" style="color:#000" placeholder="Enter full name"/>
<br><br>
Email: <br><input type="text" name="email" title="Your email address" style="color:#000" placeholder="Enter email address"/>
<br><br>
How you can help: <br><textarea cols="18" rows="3" name="help" title="Service you want to provide" style="color:#000" placeholder="Please let us know of any ways you may be of assistance"></textarea>
<br><br>
<input type="submit" value="Submit" id=submitbox"/>
</form>
</body>
<html>
Here is postest.php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$help = $_POST['help'];
$csvData = $name . "," . $email . "," . $help . '\n';
echo "Thank you for your submission! We'll get back to you as soon as we can!";
echo "I'm " . $name . ", my email is " . $email . ", and I can help in that: \n" . $help;
$filepointer = fopen('testForm.csv','a');
if ($filepointer){
fwrite($filepointer,$csvData);
fclose($filepointer);
exit();
}
?>
I checked out this question about echoing to see if that was my problem. I asked this question before and nobody seemed to find anything wrong with my code other than the obvious $_POSTEST problem. This page looked like what I was going for, but wasn't. This question kind of had what I was going for but didn't actually have the POST code and the answer was one of the most useless things I've ever read (in a nutshell: "Just do it. It isn't that complicated." and some links to other SO questions, which I followed). They brought me here and here. I put exit(); after fclose() like it seemed to work for the first one (it did nothing). With the second, the user's code was too far removed from the codes I've been looking at for me to change my code over to what he/she was doing. I've been searching a lot, and doing extensive googling, but I'm going to cut my list of research here because nobody wants to read everything; this is just to prove I tried.
Let me know if there's anything else you need; I am a complete php novice and it's probably something very basic that I missed. On the other hand, I'm not seeing any major differences between my code and others' at this point.
Try something like this :
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$help = $_POST['help'];
$filepointer = fopen('testForm.csv','a');
fputcsv($filepointer, array($name,$email, $help));
echo "Thank you for your submission! We'll get back to you as soon as we can!";
echo "I'm " . $name . ", my email is " . $email . ", and I can help in that: \n" . $help;
?>
This is the error :-
---> $filepointer = fopen('testForm.csv','a');
$fp = fopen('testForm.csv','a');
if ($fp){
fwrite($fp,$csvData);
fclose($fp);
exit();
}
And the real issue is developing without
display_errors = On
log_errors = On
Look for these parameters in the php.ini file, and turn them on, unless you are developing on a live server, in which case, you really should set up a test environment.
and then not looking at the php error log
UPDATE
There was only one line to change actually, here is the complete code.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$help = $_POST['help'];
$csvData = $name . "," . $email . "," . $help . '\n';
echo 'Thank you for your submission! We\'ll get back to you as soon as we can!';
echo '\"I\'m \"' . $name . ", my email is " . $email . ", and I can help in that: \n" . $help;
$fp = fopen('testForm.csv','a'); // only line changed
if ($fp){
fwrite($fp,$csvData);
fclose($fp);
exit();
}
?>
Your error is really basic and I am ashamed of you. Your problem is obviously that you have not been using a server, nor do you have a PHP package installed on your computer. When you told your computer target="_blank" and method="post", it knew what you wanted, being HTML. However, not having anything that parsed PHP, it had no idea how to read your code and came up as a blank page in Firefox and a block of code in Chrome.
You, indeed, have no idea what you are doing.

Returning value from powershell script can not be used with PHP

Well guys i dont really know how to start, is the first time that i work with powershell and PHP together, but now i dont know how to deal with this problem, therefore im here..
Im developing a webinterface for a company to administrate services (turn on/off servers basically). I have already programmed the powershells scripts, everything run fine 0 problems.
But i have a part where i try to show in a AlertBox(javascript) the status of a process (the powershell script has already given me the return value but i cant understand why php dont process it like a string or text.
Check it Out a piece of my code :
<?php
if (isset($_POST['button']))
{
$service = $_POST["service1"];
$psPath = "powershell.exe";
$psDIR = "C:\\xampp\\htdocs\\shell\\";
$psScript = "check-status.ps1";
$runScript = $psDIR. $psScript;
$runcheck = $psPath." ".$runScript." 2>&1";
$computername = "xen-80-42";
$go = shell_exec("$runcheck -passwd 'Hpdprqn5' -user 'Administrator' -computer '$computername' -service '$service' < NUL");
echo "<script type='text/javascript'>alert('" . $service . " is currently " . $go . " on " . $computername . "'); </script>";
}
?>
<form method="post">
<p>
<input type="text" name="service1" id="service1" maxlength="20"></input> <button name="button">Check Status</button>
</p>
</form>
Well
Everything works fine, the script give back 2 possible values : "Running" or "Stopped"
that means , the value of the variable $go, should be or "Running" or "Stopped"
Ok i tried with a process that is already running, therefore : echo $go;
print "Running"
i thought was a problem because maybe the returned value $go is not String.
But i solved that using gettype($go) , and the variable is STRING!
but can somebody explain me why when i wanna count the characters of that String, using strlen($go) , i get a return of 8 characters? RUNNING has only 7 Letters, not 8
for that reason i cant execute the ALERT in Javascript (code above), because java doesnt take it as a String or something like that
something is wrong there i think, btw when i tried to make a comparation like that:
if ($go == "Running") { echo "Everything ok"; } else { echo "different values";}
i get the second options, both values are not really equal, they are diferent. but wheree? i cant see anything..
I hope someone can helpme cause im frustrate :(
btw i tried :
strval($go);
(string)$go;
$var = "$go";
NOTHING WORKS :(
if its necesary ask for the powershell script, but i think its not necesary you see that php receives the value as STRING :/
I guess the mysterious symbol is a regular newline character. Try using trim() instead;

Javascript and PHP upload system

Thanks in advance for any help, I hope my explanation of my request is understandable.
I have a website where I upload various HTML pages with scripts, websites etc. that I have found useful over time... For the purpose of 1) a reference for myself, and 2) to share what I've found with others.
The website consists of 2 sections. A search page to find the script, and an admin page to upload it. The uploaded HTML file gets placed in a "docs/" directory on my server, and the details are added to a MySQL database for the search page.
The form looks like this:
<form name="upload" enctype="multipart/form-data" action="includes/add.php"
method="post" onsubmit="return validateForm();">
<label for="scriptname">Script Name</label><input class="inputarea" type="text"
name="scriptname"><br>
<label for="category">Category</label><input class="inputarea" type="text"
name="category"><br>
<label for="keywords">Keywords</label><input class="inputarea" type="text"
name="keywords"><br>
<label for="content">HTML File</label><input class="inputarea" type="file"
name="content"><br>
<input class="submit" type="submit" value="Add">
</form>
My question is this... Is there any way with JavaScript or PHP to do the following:
generate an automatic file name for the uploaded file (a few random digits would do)
In the "scriptname" input field, add text on submit so that it makes the Script name and file name into a hyperlink that's added to the database as text... eg. When submit button is pressed, the following is added to the database:
"scriptname_input"
Where the bold section is taken from the generated file name and the italic section is from the input field...
The purpose of this is so that in the search results, when the database column with the script name comes up, the script name is a link to the actual file. I have the search feature ready, and it is able to make a link from a database entry, but I just need to simplify the upload process.
If this is not possible, is there a different way to achieve this?
---EDIT---
Thank you all for your help! Much appreciated, I've worked it out using a combination of a few of the suggestions. However, I gave the credit to Ibere as his solution was the closest.
Here is the final code I used for the 'add.php' file that processed the upload and database addition, just in case it ever comes up again (I doubt it) :P
<?php
$filename = md5($_FILES['content']['name']);
$labelForUrl = $_POST['scriptname'];
$url = "$labelForUrl";
$target = "../docs/";
//This gets all the other information from the form
$name=$_POST['scriptname'];
$cat=$_POST['category'];
$key=$_POST['keywords'];
$link=$_POST['link'];
$file=($_FILES['content']['scriptname']);
// Connects to your Database
mysql_connect("localhost", "username", "password") or
die(mysql_error()) ;
mysql_select_db("scripts") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO scripttable (scriptname,category,keywords,link,content)
VALUES ('$url', '$cat', '$key', '$link', '$file')") ;
if(move_uploaded_file($_FILES['content']['tmp_name'], $target . $filename)) {
echo "The file ". $labelForUrl.
" has been uploaded";
}
else {
echo "There was an error uploading the file, please try again!";
}
?>
You can do something like this for the filename.
$filename = md5($_FILES['content']['name']);
$labelForUrl = $_POST['scriptname'];
md5 is not Random, but is good enough for generating a unreadable string for a filename.
Then you can create a url like this
<a href="docs/<?php echo $filename; ?>" ><?php echo $labelForUrl; ?></a>
Hope this helps.
EDIT: I forgot to add the extension to the filname. So the right code would be something like:
$filename = md5($_FILES['content']['name']).$_FILES['content']['type']
I recommend using uploadify for uploads. But, to do what you asked:
$randomFileName = rand(1000, 9999);
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $randomFileName . $_FILES["file"]["type"]);
// update your db with the location
$loc = "upload/" . $randomFileName . $_FILES["file"]["type"];
mysqli_query("insert into `myTable` (`loc`) values ('$loc')");
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
For file uploading help, look at http://www.w3schools.com/php/php_file_upload.asp
This is very easy, if you know codeigniter ( PHP Framework ).
You can use the Upload Class
You can easily create forms and submit them and also display them.
I would do it that way. If you are familiar with MVC you can do that in 10-15 mins.
To generate random file names, I usually find this does the work quite well: md5( rand( 0, 100000 ) );. If you wish to limit the size of the file name, you may use the substr function.
(Assuming a MySQL database), make the connection and then query the database using the INSERT command. This link shows how to do all of this.

Categories