I am working on a project in my college which is about developing an online autograder website like that of hackerrank for my college. Now, for compiling codes, I am using the API provided by sphere engines. The API is returning the output as a string which then I store it into a file. Then, I use a previously defined output file to compare this file and check accordingly whether the code is right or wrong. Now the problem is for eg. if output is like below:
Hello World
Hello World
Hello World
The string is written in the file as Hello WorldHello WorldHwllo World. I am using PHP to write text to file.
Is there any way to write the string as it is to a file?
Any other alternative method will also be appreciated.
Thank You.
EDIT
for eg if the code:
#include<iotsream>
using namespace std;
int main()
{
int i;
for(i=0;i<3;i++)
{
cout<<"Hello World\n";
}
return 0;
}
The output of this code should be
Hello World
Hello World
Hello World
And when i am displaying the string which is stored in a PHP array $data['output'], it is getting displayed normally but when i am writing this string to a file, It is getting stored in a single line. I want to store the string as it is i.e. in different lines.
Due to this, this file if not equal to the template output file which contains the string Hello World in different lines.
EDIT
This is the PHP code for the file which will take the source code and input and send it to the compiler and receive it's output accordingly.
<?php
error_reporting(0);
include_once '../connection-script.php';
session_start();
$user = 'xxxxx';
$pass = 'xxxxx';
$code = '';
$input = '';
$run = true;
$private = false;
$subStatus = array(
0 => 'Success',
1 => 'Compiled',
3 => 'Running',
11 => 'Compilation Error',
12 => 'Runtime Error',
13 => 'Timelimit exceeded',
15 => 'Success',
17 => 'memory limit exceeded',
19 => 'illegal system call',
20 => 'internal error'
);
$error = array(
'status' => 'error',
'output' => 'Something went wrong :('
);
//echo json_encode( array( 'hi', 1 ) ); exit;
//print_r( $_POST ); exit;
if ( isset( $_POST['process'] ) && $_POST['process'] == 1 ) {
$lang = isset( $_POST['lang'] ) ? intval( $_POST['lang'] ) : 1;
$input = trim( $_POST['input'] );
$code = trim( $_POST['source'] );
$answerfile=$_POST['answerfile'];
$outputfile=$_POST['outputfile'];
$client = new SoapClient( "http://ideone.com/api/1/service.wsdl" );
//create new submission
$result = $client->createSubmission( $user, $pass, $code, $lang, $input, $run, $private );
//if submission is OK, get the status
if ( $result['error'] == 'OK' ) {
$status = $client->getSubmissionStatus( $user, $pass, $result['link'] );
if ( $status['error'] == 'OK' ) {
//check if the status is 0, otherwise getSubmissionStatus again
while ( $status['status'] != 0 ) {
sleep( 3 ); //sleep 3 seconds
$status = $client->getSubmissionStatus( $user, $pass, $result['link'] );
}
//finally get the submission results
$details = $client->getSubmissionDetails( $user, $pass, $result['link'], true, true, true, true, true );
if ( $details['error'] == 'OK' ) {
//print_r( $details );
if ( $details['status'] < 0 ) {
$status = 'waiting for compilation';
} else {
$status = $subStatus[$details['status']];
}
$data = array(
'status' => 'success',
'meta' => "Status: $status | Memory: {$details['memory']} | Returned value: {$details['status']} | Time: {$details['time']}s",
'output' => htmlspecialchars( $details['output'] ),
'raw' => $details
);
if( $details['cmpinfo'] ) {
$data['cmpinfo'] = $details['cmpinfo'];
}
$myfile=fopen("output.txt","w");
fwrite($myfile, $data['output']);
fclose($myfile);
$qid=$_POST['questionid'];
$did=$_POST['domainid'];
if(sha1_file("output.txt") == sha1_file($outputfile))
{
$file=fopen($answerfile,"w");
fwrite($file,$code);
fclose($file);
$mail=$_SESSION['email'];
$query="SELECT * from student where semail='$mail'";
$result1=mysql_query($query);
$row1=mysql_fetch_array($result1);
$sid=$row1['studentid'];
$sql="SELECT * from practiceques where did='$did' and quesid='$qid'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$marks=$row['marks'];
$curdate=date("Y-m-d H:i:s");
$answer=mysql_query("INSERT INTO points VALUES ('$sid','$qid','$curdate',1,'$marks','$did')");
echo json_encode( $data );
}
else
{
$mail=$_SESSION['email'];
$query="SELECT * from student where semail='$mail'";
$result1=mysql_query($query);
$row1=mysql_fetch_array($result1);
$sid=$row1['studentid'];
$sql="SELECT * from practiceques where did='$did' and quesid='$qid'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$marks=$row['marks'];
$curdate=date("Y-m-d H:i:s");
$answer=mysql_query("INSERT INTO points VALUES ('$sid','$qid','$curdate',0,0,'$did')");
echo json_encode($data);
}
}
else {
//we got some error :(
//print_r( $details );
echo json_encode( $error );
}
}
else {
//we got some error :(
//print_r( $status );
echo json_encode( $error );
}
} else {
//we got some error :(
//print_r( $result );
echo json_encode( $error );
}
}
?>
You can't write with C in php document.
Anyway, This is the php code for write in file.
<?php
$fp = fopen('file.name', 'a+');
fwrite($fp, 'Hello World'.PHP_EOL);
fclose($fp);
?>
Related
I've written a simple api which lets me get the data from my database in an organised way. www.example.com/api/get/all gives me all the data from one table in the database as an array, encodes it as json and then echos it. This is used by a file which is called as a CRON job every day and dumps it (and some other data) to a .js file which the website front-end uses.
Strangely, if I go to www.example.com/api/get/all it runs for about 2-3 minutes (there is a lot of data in that table) and then outputs nothing to the screen. However, if I add an echo to the function before it loops through all the data, I get the json encoded data string outputed to the screen. Has anybody come across this before? Is it a bug? Is there a workaround?
It seems very strange that it will only echo after there has been an echo/print.
Here is the parts of my api that are relevant:
// ENDPOINT people:
private function candidates()
{
$response = new stdClass();
// Fetch all users:
if( $this->verb == 'all' )
{
// Get everyone from the DB:
$sql = $this->_db->query( 'SELECT id FROM ff_candidates' );
if( $sql )
{
$candidates = array();
while( $obj = $sql->fetchObject() )
{
// var_dump($obj);
$candidate = new Candidate( $this->_db, $obj->id );
$person = new stdClass();
// Start the response:
$person->id = $candidate->get_id();
$person->name = utf8_encode($candidate->get_name());
$person->gender = $candidate->get_gender();
$candidates[] = $person;
}
$this->_response( $candidates );
}
else
{
$response->success = false;
$response->message = 'There was a problem fetching the candidate. Please try again.';
$this->_response( $response, 500 );
}
}
}
// Send a response to the server:
private function _response( $response, $status = 200 )
{
$verbose = $this->_requestStatus( $status );
header("Content-Type: application/json");
header( 'HTTP/1.1 '.$status.' '.$verbose );
if( is_string($response) )
{
$data = new stdClass();
$data->message = $response;
$data->status = $status;
$data->title = $verbose;
}
else
{
$data = $response;
}
$json = json_encode( $data );
echo $json;
exit();
}
EDIT:
_requestStatus() code:
private function _requestStatus( $code )
{
$status = array(
200 => 'OK',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
429 => 'Too Many Requests',
500 => 'Internal Server Error',
503 => 'Service Unavailable',
);
return ( $status[$code] ) ? $status[$code] : $status[500];
}
I am trying to get the faceting results and I don't know how. there are no documentation for solr-php-client. In this example, print_r( $response->getRawResponse() ) does not include faceting. I am not sure weather faceting is not successfully requested or it is a matter of accessing the faceting data in the responce. Please also help me if there is any documentation available online for solr-php-client.
An other question is how to declare "user/password" if solr is protected when initiating the instance of solr-php-client
require_once( 'solr-php-client/Apache/Solr/Service.php' );
$solr = new Apache_Solr_Service( 'localhost', '8983', '/solr/products' );
if ( ! $solr->ping() ) {
echo 'Solr service not responding.';
exit;
}
$offset = 0;
$limit = 10;
$queries = array(
'name:iphone'
);
$additionalParameters = array(
'facet' => 'true',
'facet.field' => array(
'category'
)
);
foreach ( $queries as $query ) {
$response = $solr->search( $query, $offset, $limit );
if ( $response->getHttpStatus() == 200 ) {
print_r( $response->getRawResponse() );
if ( $response->response->numFound > 0 ) {
echo "$query <br />";
foreach ( $response->response->docs as $doc ) {
echo "$doc->id $doc->name <br />";
}
echo '<br />';
}else{
echo "zero results";
}
}
else {
echo $response->getHttpStatusMessage();
}
}
I missed to add $additionalParameters to the search arguements;
$response = $solr->search( $query, $offset, $limit,$additionalParameters );
I'm trying to save my data using php. This is how I tried:
<?php
session_start();
if(!isset($_SESSION["MemberID"])) header("Location:logout.php");
include '../config.php';
include '../momdb.php';
$page_title = "Customers";
$mode = "Save";
$db = 'db';
$showmessage = false;
$message = "";
if (isset ( $_POST ["btnSave"] )) {
$data = new table ();
$data->MomID = $_POST ["CustomerID"];
$data->CustomerName = $_POST ["CustomerName"];
$data->FromDate = string_to_date ( $_POST ["FromDate"] );
$data->ToDate = string_to_date ( $_POST ["ToDate"] );
$data->CreatedBy = $_SESSION["MemberID"];
$data->CreatedDatetime = date ( "Y-m-d H:i:s" );
$data->LastModifiedBy = $_SESSION["MemberID"];;
$data->LastModifiedDatetime = date ( "Y-m-d H:i:s" );
$rows = array ();
if (intval ( $data->CustomerID) > 0) {
$rows = $db::Update ( $data );
} else {
$rows = $db::Save ( $data );
}
if (intval ( $rows ["WebID"] ) > 0) {
$date = new DateTime ();
header ( "Location: customerlist.php?msg=yes&msgt=s&t=" . $date->getTimestamp () . "&mtext=Record saved successfully" );
} else {
$showmessage = true;
$message = $rows ["Message"];
}
} elseif (isset ( $_GET ["CustomerID"] )) {
$data = $db::GetByID ( $_GET ["CustomerID"] );
if ($data == false) {
$data = new table ();
$data->CustomerID = 0;
}
}
if ($data->CustomerID == "0")
$mode = "Save";
else
$mode = "Update";
?>
This code is for sending my values to the db page for saving them in the DB. I've used the PDO method. This is the first time I'm saving the record this way. That's why there is lots of confusion. The following code shows the Save() method, which I used to save the values to the DB.
public function Save(table $customer) {
$data = new DB ();
$stmt = $data->connection->prepare ( "CALL proc_CreateCustomer (:CustomerName, :FromDate,:ToDate,:CreatedBy, :CreatedDatetime, :LastModifiedBy, :LastModifiedDatetime)" );
$stmt->bindParam ( ':CustomerName', trim ($customer->CustomerName ));
$stmt->bindParam ( ':FromDate', $customer->FromDate );
$stmt->bindParam ( ':ToDate', $customer->ToDate);
$stmt->bindParam ( ':CreatedBy',$customer->CreatedBy );
$stmt->bindParam ( ':CreatedDatetime', $customer->CreatedDatetime );
$stmt->bindParam ( ':LastModifiedBy',$customer->LastModifiedBy );
$stmt->bindParam ( ':LastModifiedDatetime', $customer->LastModifiedDatetime );
$stmt->execute ();
$record = $stmt->fetch ( PDO::FETCH_OBJ );
if ($record == false) {
return array (
"WebID" => 0,
"Message" => $record->Message,
"AppID" => $customer->AndroidID
);
} else {
return array (
"WebID" => $record->CustomerID,
"Message" => $record->Message,
"AppID" => $customer->AndroidID
);
}
}
This is how I've tried. But, whenever I try to save the details, it shows: " Trying to get property of non-object in D:\Workspace\Application\momdb.php on line 39", ie it shows error in the line "Message" => $record->Message,"AppID" => $customer->AndroidID. I don't what's wrong with this. Can someone tell me what should I change so that it work fine?
if ($record == false) {
return array (
"WebID" => 0,
"Message" => $record->Message,
"AppID" => $customer->AndroidID
);
}
In this piece of code $record is false(y), so $record->Message doesn't exist.
I would like to check a custom form against spam using Akismet.
I searched the web and the only simple way I found is this (see code excerpt below): http://www.binarymoon.co.uk/2010/03/akismet-plugin-theme-stop-spam-dead/. Unfortunately $isSpam returns true!
Does anyone know how to do the magic? I appreciate your help.
function akismet_isSpam ($content) {
// innocent until proven guilty
$isSpam = FALSE;
$content = (array) $content;
if (function_exists('akismet_init')) {
$wpcom_api_key = get_option('wordpress_api_key');
if (!empty($wpcom_api_key)) {
global $akismet_api_host, $akismet_api_port;
// set remaining required values for akismet api
$content['user_ip'] = preg_replace( '/[^0-9., ]/', '', $_SERVER['REMOTE_ADDR'] );
$content['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
$content['referrer'] = $_SERVER['HTTP_REFERER'];
$content['blog'] = get_option('home');
if (empty($content['referrer'])) {
$content['referrer'] = get_permalink();
}
$queryString = '';
foreach ($content as $key => $data) {
if (!empty($data)) {
$queryString .= $key . '=' . urlencode(stripslashes($data)) . '&';
}
}
$response = akismet_http_post($queryString, $akismet_api_host, '/1.1/comment-check', $akismet_api_port);
smart_dump($response, true);
if ($response[1] == 'true') {
update_option('akismet_spam_count', get_option('akismet_spam_count') + 1);
$isSpam = TRUE;
}
}
}
return $isSpam;
}
First , you can assume akismet is installed and API key verified, that will allow you to use the akismet_http_post function directly to post the data to servers ..
// Like above mentioned, We assume that :
// Akismet is installed with the corresponding API key
if( function_exists( 'akismet_http_post' ) )
{
global $akismet_api_host, $akismet_api_port;
// data to be delivered to Akismet (This is what you need Modify this to your needs)
$data = array(
'comment_author' => 'Spammer Spammy',
'comment_author_email' => 'spammy#spamserver.com',
'comment_author_url' => 'spamming.com',
'comment_content' => 'my Spam',
'user_ip' => '99.99.99.99',
'user_agent' => '',
'referrer' => '',
'blog' => 'http://example.com',
'blog_lang' => 'en_US',
'blog_charset' => 'UTF-8',
'permalink' => 'http://example.com/my-link',
'is_test' => TRUE,
);
// Now we need to construct the query string
$query_string = http_build_query( $data );
// and then post it to Akismet
$response = akismet_http_post( $query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port );
// ..and check the results
$result = ( is_array( $response ) && isset( $response[1] ) ) ? $response[1] : 'false';
// display the result ( 'true', 'false' or any error message you want )
printf( 'Spam check according to Akismet :%s', $result );
}
This was not thoroughly tested , but should work..
Note that the blog, user_ip and user_agent parameters are required for the akismet_http_post function.
Also, it would be nice to mention that Akismet has libraries and good API documents .
I would like to be able to set a global username like <anythinghere>#domain3.com as a username value in the $usernames array (in code below). This is so that I can then go and redirect users based on domain, having already been "authenticated".
I will put example in code below.
Can i do something like $usernames = array("username#domain1.com", $X) where $X = <anything-so-long-as-not-blank>#domain3.com?
Full Code Below:
<?php
//VALIDATE USERS
$usernames = array("username#domain1.com", "username2#domain1.com", "username3#domain1.com", "username1#domain2.com", "username2#domain2.com", "username1#domain3.com");
$passwords = array("password1", "password2", "password3", "password4", "password5", "password6");
//REDIRECT SPECIFIC VALID USERS OR DOMAIN
function get_page($username) {
$username = strtolower($username);
switch ($username) {
case "username#domain1.com" : return "http://www.google.com";
case "username2#domain1.com" : return "http://www.yahoo.com";
case "username3#domain1.com" : return "http://www.stackoverflow.com";
case "username1#domain2.com" : return "http://www.serverfault.com";
}
return preg_match('/#domain3\.com$/',$username) ?
"http://www.backblaze.com" : "DefaultBackupPage.php";
}
$page = get_page($_POST['username']);
for($i=0;$i<count($usernames);$i++)
{
$logindata[$usernames[$i]]=$passwords[$i];
}
$found = 0;
for($i=0;$i<count($usernames);$i++)
{
if ($usernames[$i] == $_POST["username"])
{
$found = 1;
}
}
if ($found == 0)
{
header('Location: login.php?login_error=1');
exit;
}
if($logindata[$_POST["username"]]==$_POST["password"])
{
session_start();
$_SESSION["username"]=$_POST["username"];
header('Location: '.$page);
exit;
}
else
{
header('Location: login.php?login_error=1');
exit;
}
?>
#inhan Has already helped me like a champ. I am wondering if any one can get me over the line? Cheers!
Your code needed a clean-up first. There's a bunch of errors in it if you do a test run. It's also a bit hard to read IMO.
I've attached a working code sample below.
// Get users
$input_pwd = ( isset( $_POST["password"] ) ? $_POST["password"] : '' );
$input_user = ( isset( $_POST["username"] ) ? $_POST["username"] : '' );
// Your pseudo database here ;)
$usernames = array(
"username#domain1.com",
"username2#domain1.com",
"username3#domain1.com",
"username1#domain2.com",
"/[a-z][A-Z][0-9]#domain2\.com/", // use an emtpy password string for each of these
"/[^#]+#domain3\.com/" // entries if they don't need to authenticate
);
$passwords = array( "password1", "password2", "password3", "password4", "", "" );
// Create an array of username literals or patterns and corresponding redirection targets
$targets = array(
"username#domain1.com" => "http://www.google.com",
"username2#domain1.com" => "http://www.yahoo.com",
"username3#domain1.com" => "http://www.stackoverflow.com",
"username1#domain2.com" => "http://www.serverfault.com",
"/[a-z][A-Z][0-9]#domain2\.com/" => "http://target-for-aA1-usertypes.com",
"/[^#]+#domain3\.com/" => "http://target-for-all-domain3-users.com",
"/.+/" => "http://default-target-if-all-else-fails.com",
);
$logindata = array_combine( $usernames, $passwords );
if ( get_user_data( $input_user, $logindata ) === $input_pwd ) {
session_start();
$_SESSION["username"] = $input_user;
header('Location: ' . get_user_data( $input_user, $targets ) );
exit;
} else {
// Supplied username is invalid, or the corresponding password doesn't match
header('Location: login.php?login_error=1');
exit;
}
function get_user_data ( $user, array $data ) {
$retrieved = null;
foreach ( $data as $user_pattern => $value ) {
if (
( $user_pattern[0] == '/' and preg_match( $user_pattern, $user ) )
or ( $user_pattern[0] != '/' and $user_pattern === $user)
) {
$retrieved = $value;
break;
}
}
return $retrieved;
}