PHP to ASP.NET conversion - php

Does anyone know how to convert the following PHP code to ASP.NET?
<?php
$myFile = "includes/status.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 1);
$status= $theData;
if ( $status == 0) {
include('includes/bol_down.php');
}
elseif ($status == 1){
include('includes/login_form_up.php');
}
fclose($fh);
?>

Probably depends a lot on what's being included. ASP.NET doesn't "include" other code in this manner.
If the code being included is just PHP code, then there's no need for this in ASP.NET. The compiled assembly has all of the available code from the compilation already available.
If the code being included is actual page output, then it's a different model for how you'd accomplish this. The closest analogy would be to conditionally display a user control. Something like this:
if (status == 0)
{
var myControl = (MyControlType)LoadControl("~/MyControl.ascx");
myPlaceHolder.Controls.Add(myControl);
}
else if (status == 1)
{
var myOtherControl = (MyOtherControlType)LoadControl("~/MyOtherControl.ascx");
myPlaceHolder.Controls.Add(myOtherControl);
}
In this case, myPlaceHolder is an existing control on the page which exists solely as a, well, placeholder in order to add controls dynamically. This is because the page life cycle is different in ASP.NET than in PHP. In PHP the scripts are added in-line, whereas in ASP.NET the user controls are inserted into existing markup structure.

int status = theData;
if(status == 0)
{
Response.WriteFile("includes/bol_down.html");
}
else if(status == 1)
{
Response.WriteFile("includes/login_form_up.html");
}
I'm assuming theData is of type int (integer).
Couple things to note. ASP.NET precompiles before deployment which is why you can't dynamically add using include. Instead, you have to write the file directly to the output stream (WriteFile()). Also, the file you include can't contain ASP.NET server side code. If it does, the code won't be executed, it will simply be displayed to the user. There may be an alternative to what you're trying to achieve. You can read more on dynamically including the file here.

<?php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
include_once "ez_sql_core.php";
include_once "ez_sql_mysql.php";
$db = new ezSQL_mysql('db_user','db_password','db_name','db_host');
$song = $db->get_row("SELECT * FROM songs ORDER BY RAND() LIMIT 1");
$artist = $song->artist;
$songname = $song->title;
$url = $song->url;
$separator = '|';
echo $url.$separator.$artist.$separator.$songname;
}
?>

Related

php check if browser tab was opened with "target=" - and what target it was

I am opening two windows in one session, which should have different behaviours. As the windows open at the same time, they are using th same options and interfering with each other. Therefore I would need to check in the code, how they were opened.
If it was opened with something like
window.open(href, target='pdf');
I would want to check this
if(tab.target = "pdf")
{
$check_target = 1
}
else
{
$check_target = 2
}
now "tab.target" does not exist - can I achieve this somehow?
Thanks!
Max
I would add a something to the url like this:
window.open(href+'?mytarget=pdf', target='pdf');
Then in your php code:
if($_GET['mytarget'] == "pdf")
{
$check_target = 1;
}
else
{
$check_target = 2;
}

PHP Not loading rest of page after exit;

I'm very new to PHP, and I can't figure out why this is happening.
For some reason, when exit fires the entire page stops loading, not just the PHP script. Like, it'll load the top half of the page, but nothing below where the script is included.
Here's my code:
$page = $_GET["p"] . ".htm";
if (!$_GET["p"]) {
echo("<h1>Please click on a page on the left to begin</h1>\n");
// problem here
exit;
}
if ($_POST["page"]) {
$handle = fopen("../includes/$page", "w");
fwrite($handle, $_POST["page"]);
fclose($handle);
echo("<p>Page successfully saved.</p>\n");
// problem here
exit;
}
if (file_exists("../includes/$page")) {
$FILE = fopen("../includes/$page", "rt");
while (!feof($FILE)) {
$text .= fgets($FILE);
}
fclose($FILE);
} else {
echo("<h1>Page "$page" does not exist.</h1>\n");
// echo("<h1>New Page: $page</h1>\n");
// $text = "<p></p>";
// problem here
exit;
}
Even if you have HTML code following your PHP code, from the web server's perspective it is strictly a PHP script. When exit() is called, that is the end of it. PHP will output process and output no more HTML, and the web server will not output anymore html. In other words, it is working exactly as it is supposed to work.
If you need to terminate the flow of PHP code execution without preventing any further HTML from being output, you will need to reorganize your code accordingly.
Here is one suggestion. If there is a problem, set a variable indicating so. In subsequent if() blocks, check to see if previous problems were encountered.
$problem_encountered = FALSE;
if (!$_GET["p"]) {
echo("<h1>Please click on a page on the left to begin</h1>\n");
// problem here
// Set a boolean variable indicating something went wrong
$problem_encountered = TRUE;
}
// In subsequent blocks, check that you haven't had problems so far
// Adding preg_match() here to validate that the input is only letters & numbers
// to protect against directory traversal.
// Never pass user input into file operations, even checking file_exists()
// without also whitelisting the input.
if (!$problem_encountered && $_GET["page"] && preg_match('/^[a-z0-9]+$/', $_GET["page"])) {
$page = $_GET["p"] . ".htm";
$handle = fopen("../includes/$page", "w");
fwrite($handle, $_GET["page"]);
fclose($handle);
echo("<p>Page successfully saved.</p>\n");
// problem here
$problem_encountered = TRUE;
}
if (!$problem_encountered && file_exists("../includes/$page")) {
$FILE = fopen("../includes/$page", "rt");
while (!feof($FILE)) {
$text .= fgets($FILE);
}
fclose($FILE);
} else {
echo("<h1>Page "$page" does not exist.</h1>\n");
// echo("<h1>New Page: $page</h1>\n");
// $text = "<p></p>";
// problem here
$problem_encountered = TRUE;
}
There are lots of ways to handle this, many of which are better than the example I provided. But this is a very easy way for you to adapt your existing code without needing to do too much reorganization or risk breaking much.
In PHP 5.3+ you can use the goto statement to jump to a label just before the ?> instead of using exit in the example given in the question.
It would'n work well with more structured code (jumping out of functions), tough.
Maybe this should be a comment, who knows.

session_start() issue

today one of my friends had a problem with his guestbook. We use a small php orientated guestbook which was working fine except for one thing: it had reached its limit of messages.
So what i did is edit the blog file and change the following setting:
//Maximum entry stored in data file
$max_record_in_data_file = 1800;
The moment I did this though, something went very wrong. I uploaded the file back on the server and got the following:
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at E:\inetpub\vhosts\trilogianocturnus.com\httpdocs\guestbook.php:1) in E:\inetpub\vhosts\trilogianocturnus.com\httpdocs\guestbook.php on line 95
I don't know what this is, I'm very new to php, but from what I understand, it means something is already being called by the browser before session_start
The page is located at:
http://trilogianocturnus.com/guestbook.php
The code before the head is as follows:
<?
/*-----------------------------------------------------
COPYRIGHT NOTICE
Copyright (c) 2001 - 2008, Ketut Aryadana
All Rights Reserved
Script name : ArdGuest
Version : 1.8
Website : http://www.promosi-web.com/script/guestbook/
Email : aryasmail#yahoo.com.au
Download URL :
- http://www.promosi-web.com/script/guestbook/download/
- http://www.9sites.net/download/ardguest_1.8.zip
This code is provided As Is with no warranty expressed or implied.
I am not liable for anything that results from your use of this code.
------------------------------------------------------*/
//--Change the following variables
//Title of your guestbook
$title = "Guestbook Nocturnus";
//Change "admin" with your own password. It's required when you delete an entry
$admin_password = "***";
//Enter your email here
$admin_email = "***";
//Your website URL
$home = "http://www.trilogianocturnus.com/main.html";
//Send you an email when someone add your guestbook, YES or NO
$notify = "YES";
//Your Operating System
//For Windows/NT user : WIN
//For Linux/Unix user : UNIX
$os = "WIN";
//Maximum entry per page when you view your guestbook
$max_entry_per_page = 10;
//Name of file used to store your entry, change it if necessary
$data_file = "ardgb18.dat";
//Maximum entry stored in data file
$max_record_in_data_file = 1800;
//Maximum entries allowed per session, to prevent multiple entries made by one visitor
$max_entry_per_session = 10;
//Enable Image verification code, set the value to NO if your web server doesn't support GD lib
$imgcode = "YES";
//Color & font setting
$background = "#000";
$table_top = "#000";
$table_content_1a = "#090909";
$table_content_1b = "#000000";
$table_content_2a = "#090909";
$table_content_2b = "#000000";
$table_bottom = "#000";
$table_border = "#1f1f1f";
$title_color = "#9f0000";
$link = "#9f0000";
$visited_link = "#9f0000";
$active_link = "#9f0000";
$font_face = "verdana";
$message_font_face = "arial";
$message_font_size = "2";
//-- Don't change bellow this line unless you know what you're doing
$do = isset($_REQUEST['do']) ? trim($_REQUEST['do']) : "";
$id = isset($_GET['id']) ? trim($_GET['id']) : "";
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$self = $_SERVER['PHP_SELF'];
if (!file_exists($data_file)) {
echo "<b>Error !!</b> Can't find data file : $data_file.<br>";
exit;
} else {
if ($max_record_in_data_file != "0") {
$f = file($data_file);
rsort($f);
$j = count($f);
if ($j > $max_record_in_data_file) {
$rf = fopen($data_file,"w");
if (strtoupper($os) == "UNIX") {
if (flock($rf,LOCK_EX)) {
for ($i=0; $i<$max_record_in_data_file; $i++) {
fwrite($rf,$f[$i]);
}
flock($rf,LOCK_UN);
}
} else {
for ($i=0; $i<$max_record_in_data_file; $i++) {
fwrite($rf,$f[$i]);
}
}
fclose($rf);
}
}
}
session_start();
$newline = (strtoupper($os) == "WIN") ? "\r\n" : "\n";
switch ($do) {
case "":
$record = file($data_file);
rsort($record);
$jmlrec = count($record);
?>
I have of course, removed the password and email for security, now here isthe funny part.
This error started happening the moment i changed that setting up up there, but if i tried to revert it back to 1800 (i changed it to 11800 to test it out), it still gives me that error.
Any idea of what this is?
The guestbook url is: promosi-web.com/script/guestbook/
The most common cause of this error is something being added to the file before the <?
Most likely a space or UTF byte order mark.
Put your session_start() after <? and you should be fine
Note:
To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
http://php.net/manual/en/function.session-start.php
The message says that the “output started at …\guestbook.php:1”. So there must be something in that file on that line that initiated the output.
Make sure that there are no whitespace or other invisible characters (like a BOM) before the opening <? tag.
Check if you have a space or a byte order mark, you can also do an
ob_start(); at the beginning of the page and ob_end_flush(); at the end to solve this issue.
but IMO check for the space or the B.O.M

How can I use a php file's output with Ajax?

I was following this tutorial.
I need to use a php file's ouput in my HTML file to dynamically load images into a gallery. I call
function setOutput()
{
if (httpObject.readyState == 4)
document.getElementById('main').src = httpObject.responseText;
alert("set output: " + httpObject.responseText);
}
from
function doWork()
{
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "gallery.php?no=0", true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
However, the alert returns the php file, word for word. It's probably a really stupid error, but I can't seem to find it.
The php file:
<?php
if (isset($_GET['no'])) {
$no = $_GET['no'];
if ($no <= 10 && $no >1) {
$xml = simplexml_load_file('gallery.xml');
echo "images/" . $xml->image[$no]->src;
}
else die("Number isn't between 1 and 10");
}
else die("No number set.");
?>
If the alert is returning the contents of the PHP file instead of the results of executing it, then the server is not executing it.
Test by accessing the URI directly (instead of going via JavaScript).
You probably need to configure PHP support on the server.
Your Server doesn't serve/parse PHP files! You could test your JavaScript code by setting the content of gallery.php to the HTML code you want to receive.

PHP variable from external .php file, inside JavaScript?

I have got this JavaScript code for uploading files to my server (named it "upload.js"):
function startUpload(){
document.getElementById('upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is [HERE I NEED THE VARIABLE FROM THE EXTERNAL PHP FILE]!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
And I've got a simple .php file that process uploads with renaming the uploaded files (I named it "process_file.php"), and connects again with upload.js to fetch the result:
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit = rand(0000,9999);
$new_file_name = $random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>
What I need is inside upload.js to visualize the new name of the uploaded file as an answer if the upload process has been correct? I wrote inside JavaScript code above where exactly I need to put the new name answer.
You have to change your code to the following.
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo "message" ?>');</script>
And your JavaScript code,
function stopUpload(success, message){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is '+message+'!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
RageZ's answer was just about what I was going to post, but to be a little more specific, the last line of your php file should look like this:
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo $new_file_name ?>');</script>
The javascript will error without quotes around that second argument and I'm assuming $new_file_name is what you want to pass in. To be safe, you probably even want to escape the file name (I think in this case addslashes will work).
A dumb man once said; "There are no stupid questions, only stupid answers". Though he was wrong; there are in fact loads of stupid questions, but this is not one of them.
Besides that, you are stating that the .js is uploading the file. This isn't really true.
I bet you didn't post all your code.
You can make the PHP and JavaScript work together on this problem by using Ajax, I recommend using the jQuery framework to accomplish this, mostly because it has easy to use functions for Ajax, but also because it has excellent documentation.
How about extending the callback script with:
window.top.window.stopUpload(
<?php echo $result; ?>,
'<?php echo(addslashes($new_file_name)); ?>'
);
(The addslashes and quotes are necessary to make the PHP string come out encoded into a JavaScript string literal.)
Then add a 'filename' parameter to the stopUpload() function and spit it out in the HTML.
$new_file_name=$random_digit.$file_name;
Sorry, that is not sufficient to make a filename safe. $file_name might contain segments like ‘x/../../y’, or various other illegal or inconsistently-supported characters. Filename sanitisation is much harder than it looks; you are better off making up a completely new (random) file name and not relying on user input for it at all.

Categories