This question already has answers here:
PHP cli getting input from user and then dumping into variable possible?
(4 answers)
Closed 6 years ago.
I have a php file named test.php.In that file I have to take two inputs which are number and message.I wish to execute this php file from command prompt.The problem is that after executing the php file it should ask me for inputs but it isn't doing that.My code is below
echo "ENTER YOUR NUMBER";
$num = $_GET["number"];
echo "Enter your message";
$msg = $_GET["message"];
echo $num;
echo $msg;
Can someone help me with it?
My test.php file now contains the following code
echo "ENTER YOUR NUMBER";
$num = trim(fgets(STDIN));
echo "Enter your message";
$msg = trim(fgets(STDIN));
$post['num'] = $num;
$post['msg'] = $msg;
$url = 'http://172.16.1.223/source%20codes/wc.php';
$fields = array(
'num'=>urlencode($post["num"]),
'msg'=>urlencode($post["msg"])
);
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);
$response = curl_exec($ch)
I am trying to access another file wc.php which is on another computer through ip address and using curl.Problem is that I am not understanding in wc.php file is the input taking format is correct or not.wc.php file contains the following code
$num=trim(fgets(STDIN));
$msg=trim(fgets(STDIN));
echo $num;
echo $msg;
I just want to pass the variables from test.php to wc.php
you can do this:
$input = trim(fgets(STDIN));
fgets takes input from STDIN and waits for a linebreak.
The trim function makes sure you don't have that line break at the end.
So to add this in your example:
echo "ENTER YOUR NUMBER";
$num = trim(fgets(STDIN));
echo "Enter your message";
$msg = trim(fgets(STDIN));
echo $num;
echo $msg;
When working on the command line, you won't be able to use the superglobals ($_GET, $_REQUEST, etc.) like you can when using PHP on a website. You will want to pass the values in on the command line like this:
php -f myfile.php /number:"40" /message:"this is great"
You can then access the command line arguments with $argv.
Related
I have a PHP IMAP code I wrote that makes me manually type in my email and password to validate/authenticate. If I input a wrong password it gives me "not connect" and if I type in my right password it displays "CONNECT".
<?php
$email = $_REQUEST['email'];
$domcom = trim(strstr($email, '#'), '#');
$mbox = imap_open("{mail.$domcom:993/imap/ssl/novalidate-cert/notls}", "user#domain.com", "password");
if ($mbox == true)
{
echo "CONNECT";
}
else
{
echo "NOT CONNECT";
}
?>
So what I need is I don't want to manually type it myself again. I need help with fixing the script for it to do the work automatically, that I have my email:password like this in a log.txt file in the format below:
user1#domain.com:password1
user2#domain.com:password2
user3#domain.com:password3
user4#domain.com:password4
use5#domain.com:password5
use6#domain.com:password6
use7#domain.com:password7
user8#domain.com:password8
user9#domain.com:password9
user10#domain.com:password10
user11#domain.com:password11
user12#domain.com:password12
So, if I run the imap.php script on browser it checks them automatically line by line till it finishes, and gives me "good.txt" for authenticated login that connects and "bad.txt" for bad login.
Note: I want the IMAP server in quote "" to remain the same.
{mail.$domcom:993/imap/ssl/novalidate-cert/notls}
Make $domcom call the domain part in each line of the txt and post it on the IMAP server line of code.
Kindly put below code in your imap.php
<?php
$lines = file('log.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($lines as $line){
list($email, $password) = explode(':', $line);
$domcom = trim(strstr($email, '#'), '#');
$mbox = imap_open("mail.{$domcom}:993/imap/ssl/novalidate-cert/notls", $email, $password);
if( $mbox == true ){
file_put_contents('good.txt', $line."\n", FILE_APPEND);
}else{
file_put_contents('bad.txt', $line."\n", FILE_APPEND);
}
}
?>
And below in the log.txt
user1#domain.com:password1
user2#domain.com:password2
user3#domain.com:password3
user4#domain.com:password4
use5#domain.com:password5
use6#domain.com:password6
use7#domain.com:password7
user8#domain.com:password8
user9#domain.com:password9
user10#domain.com:password10
user11#domain.com:password11
user12#domain.com:password12
Source
file() - https://www.php.net/manual/en/function.file.php
file_put_contents() - https://www.php.net/manual/en/function.file-put-contents.php
this is my first time using PHP, so I'm here because I don't even know how to look for the information I want (function name's, properties, etc). As I said before, my code receives a string with two variables and uploads it to a log with the format:
Raw time data, var1, var2
So, I want to add some lines that allow the code to send an "OK" confirmation when data has been successfully posted. How can I get it?
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
echo "<pre>";
echo "hello! \n";
$file = 'measures.txt';
$time = time();
$row = "$time";
if ( isset( $_GET["T"] ) )
{
$new_measure = $_GET["T"];
echo "Temperature: $new_measure \n";
$row = $row.", $new_measure";
} else {
$row = $row.", ";
}
if ( isset( $_GET["H"] ) )
{
$new_measure = $_GET["H"];
echo "Humidity: $new_measure \n";
$row = $row.", $new_measure";
} else {
$row = $row.", ";
}
file_put_contents($file, "$row\n", FILE_APPEND | LOCK_EX);
echo "</pre>";
?>
Julio,
in your file_put_contents function you could simply echo a " OK" message if the file is successfully stored in the location you set. Now if you are trying to do email confirmation you would need to setup a mail function within your php application and have the proper smtp configurations so your server can do that.
I am assuming you have verification checks before the file is given to your file_put_contents function.
In an assignment I'm having trouble running a php script with page handling. It's outputting actual php code when submitted through another php page but works fine on its own.
I have a html login page which submits via submit buttons rather than form submit [a requirement]. This submits to login.php.
Seperately I have testBalance.php which checks a file balance.txt on my server which simply has an amount (1000). testBalance.php calls a function in getBalance.php to return the amount here.
THE PROBLEM IS when I run testBalance.php by itself it works just fine. Displaying "Account Balance: 1000.00" but when I attempt to set (in login.php) testBalance.php as the redirect url, the page literally displays code from my testBalance.php page: "Account balance: "); printf ( "%01.2f", $returnValue ); echo ("
"); ?> " I know it's convoluted, this is an intro to php portion of an web prog. class. I'm guessing it has to do with the value pairs that are being passed through to the pages. Can anyone help?
LOGIN.HTML snippit
<input type="button" name="sub_but" id="bal" value="check balance"
onclick="location.href = 'login.php' + '?' + 'name='+ document.forms[0].username.value +
'&redirectURL=' + 'bal';" />
LOGIN.PHP
<?php
$NAME=$_GET["name"];
$PAGE=$_GET["redirectURL"];
$DESTINATION="";
if ($NAME == ''){ /* HANDLES NAME ERRORS */
echo "PLEASE RETURN AND ENTER A NAME.";
}
elseif (ctype_alpha(str_replace(' ', '', $NAME)) === false) {
echo "$NAME is not a valid name. Name must contain letters and spaces only";
}
else{
if($PAGE=='with'){
$DESTINATION = "withdraw.html";
}
elseif($PAGE=='bal'){
//$DESTINATION = "balance.html";
$DESTINATION = "testBalance.php";
}
elseif($PAGE=='depos'){
$DESTINATION = "deposit.html";
}
elseif($PAGE=='weath'){
$DESTINATION = "weather.html";
}
elseif($PAGE=='xchang'){
$DESTINATION = "currency.html";
}
/*echo("$DESTINATION\r\n");*/
header("Content-Length: " .
strlen(file_get_contents($DESTINATION)));
header("Cache-Control: no-cache");
readfile($DESTINATION);
}
?>
testBalance.php body snippit
<?php
include 'getBalance.php';
$returnValue = readBalance();
echo "<p>Account balance: ";
printf( "%01.2f", $returnValue );
echo "</p>";
?>
getBalance.php
<?php
function readBalance(){
$file = "balance.txt";
$fp = fopen($file, "r");
if (!$fp){
echo "<p>Could not open the data file.</p>";
$balance = 0;
}
else{
$balance = fgets($fp);
fclose ($fp);
}
return $balance;
}
?>
readfile() doesn't EXECUTE anything it reads. It's literally just slurping in the file's bytes and spitting them out to the client. It's basically doing
echo file_get_contents(...);
If you want your other files to be executed, you need to include() or require() them instead. Or you could try eval(), but you really don't want to go down that route. eval() is evil and dangerous.
I am trying to validate my name's text box so even if they by pass it it won't still accept the name with spcial characters like "!##$%^&*()_" and numbers too and this is my code:
public function updateuserAction(){
$this->view->disable();
$get = $this->request;
$key = $get->get('key');
$email = $get->get('email');
$password = $get->get('password');
$realName = $get->get('realName');
$type = $get->get('userType');
if(filter_var($realname, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => "/^[a-zA-Z]+$/")))){
$url = $this->apiUrl."user/update?q=(key:$key,email:".urlencode($email).",password:".urlencode($password).",realName:".urlencode($realName).",userType:".urlencode($type).")&envelope=false";
$ch = curl_init($url);
curl_setopt_array($ch, $this->curlopt);
echo curl_exec($ch);
}else {
echo "Failed";
}
}
this is my code i don't know how to insert validation here. it always give me an error message whenever i add validation code here. I am a newbie in this line so if could help it would mean alot to e. thanks!
I already added my trial code
The php regular expression matching function is - preg_match.
Your question is a bit vague but from what I can gather you want to validate that the username contains only alphabet characters. As such try something like
if (preg_match("^[a-zA-Z]+$") == false)
{
echo "Username is invalid.";
die(); // or some other error handling code
}
Aww man, now i know what's making my code always fall on failed -- just because of $realname to $realName -- i forgot it's case sensitive. thanks for your efforts to answer guys :D
How can you mimic a command line run of a script with arguements inside a PHP script? Or is that not possible?
In other words, let's say you have the following script:
#!/usr/bin/php
<?php
require "../src/php/whatsprot.class.php";
function fgets_u($pStdn) {
$pArr = array($pStdn);
if (false === ($num_changed_streams = stream_select($pArr, $write = NULL, $except = NULL, 0))) {
print("\$ 001 Socket Error : UNABLE TO WATCH STDIN.\n");
return FALSE;
} elseif ($num_changed_streams > 0) {
return trim(fgets($pStdn, 1024));
}
}
$nickname = "WhatsAPI Test";
$sender = ""; // Mobile number with country code (but without + or 00)
$imei = ""; // MAC Address for iOS IMEI for other platform (Android/etc)
$countrycode = substr($sender, 0, 2);
$phonenumber=substr($sender, 2);
if ($argc < 2) {
echo "USAGE: ".$_SERVER['argv'][0]." [-l] [-s <phone> <message>] [-i <phone>]\n";
echo "\tphone: full number including country code, without '+' or '00'\n";
echo "\t-s: send message\n";
echo "\t-l: listen for new messages\n";
echo "\t-i: interactive conversation with <phone>\n";
exit(1);
}
$dst=$_SERVER['argv'][2];
$msg = "";
for ($i=3; $i<$argc; $i++) {
$msg .= $_SERVER['argv'][$i]." ";
}
echo "[] Logging in as '$nickname' ($sender)\n";
$wa = new WhatsProt($sender, $imei, $nickname, true);
$url = "https://r.whatsapp.net/v1/exist.php?cc=".$countrycode."&in=".$phonenumber."&udid=".$wa->encryptPassword();
$content = file_get_contents($url);
if(stristr($content,'status="ok"') === false){
echo "Wrong Password\n";
exit(0);
}
$wa->Connect();
$wa->Login();
if ($_SERVER['argv'][1] == "-i") {
echo "\n[] Interactive conversation with $dst:\n";
stream_set_timeout(STDIN,1);
while(TRUE) {
$wa->PollMessages();
$buff = $wa->GetMessages();
if(!empty($buff)){
print_r($buff);
}
$line = fgets_u(STDIN);
if ($line != "") {
if (strrchr($line, " ")) {
// needs PHP >= 5.3.0
$command = trim(strstr($line, ' ', TRUE));
} else {
$command = $line;
}
switch ($command) {
case "/query":
$dst = trim(strstr($line, ' ', FALSE));
echo "[] Interactive conversation with $dst:\n";
break;
case "/accountinfo":
echo "[] Account Info: ";
$wa->accountInfo();
break;
case "/lastseen":
echo "[] Request last seen $dst: ";
$wa->RequestLastSeen("$dst");
break;
default:
echo "[] Send message to $dst: $line\n";
$wa->Message(time()."-1", $dst , $line);
break;
}
}
}
exit(0);
}
if ($_SERVER['argv'][1] == "-l") {
echo "\n[] Listen mode:\n";
while (TRUE) {
$wa->PollMessages();
$data = $wa->GetMessages();
if(!empty($data)) print_r($data);
sleep(1);
}
exit(0);
}
echo "\n[] Request last seen $dst: ";
$wa->RequestLastSeen($dst);
echo "\n[] Send message to $dst: $msg\n";
$wa->Message(time()."-1", $dst , $msg);
echo "\n";
?>
To run this script, you are meant to go to the Command Line, down to the directory the file is in, and then type in something like php -s "whatsapp.php" "Number" "Message".
But what if I wanted to bypass the Command Line altogether and do that directly inside the script so that I can run it at any time from my Web Server, how would I do that?
First off, you should be using getopt.
In PHP it supports both short and long formats.
Usage demos are documented at the page I've linked to. In your case, I suspect you'll have difficulty detecting whether a <message> was included as your -s tag's second parameter. It will probably be easier to make the message a parameter for its own option.
$options = getopt("ls:m:i:");
if (isset($options["s"] && !isset($options["m"])) {
die("-s needs -m");
}
As for running things from a web server ... well, you pass variables to a command line PHP script using getopt() and $argv, but you pass variables from a web server using $_GET and $_POST. If you can figure out a sensible way to map $_GET variables your command line options, you should be good to go.
Note that a variety of other considerations exist when taking a command line script and running it through a web server. Permission and security go hand in hand, usually as inverse functions of each other. That is, if you open up permissions so that it's allowed to do what it needs, you may expose or even create vulnerabilities on your server. I don't recommend you do this unless you'll more experienced, or you don't mind if things break or get attacked by script kiddies out to 0wn your server.
You're looking for backticks, see
http://php.net/manual/en/language.operators.execution.php
Or you can use shell_exec()
http://www.php.net/manual/en/function.shell-exec.php