I am just beginning to learn PHP, so I apologize if this is a basic question. I am using what I understand to be a CodeIgniter-like MVC framework (NOT CI though - a homegrown framework)
I am trying to pass two parameters to my index controller, each of which will display a different error message. The errors are generated from two individual post functions (i.e., if user's log in is incorrect and if email already exists at sign up).
public function index($error1=NULL, $error2=NULL) {
$this->template->content = View::instance('v_index_index');
$this->template->content->error1 = $error1;
$this->template->content->error2 = $error2;
echo $this->template;
}
What I am observing is that the only error displayed is the parameter that appears in the parentheses first (e.g., at index/index/error2 the error1 message is displayed). I've already tested the logic for determining the error type, so I know that is correct and believe it must have something to do with the above.
Any help is greatly appreciated!
Related
I've been looking around at similar topics on REST APIs but I am still having some confusion in my project, mostly with the PHP side of things.
USPS provides a REST API with functions that can be called via URL like this: https://epfws.usps.gov/ws/resources/epf/login
To make any call successfully, I have been told that a JSON object must be created and passed as a "POST parameter" with the expected values.
This is the JSON object that needs to be passed in this case:
obj=
{
"login":"loginExample",
"pword":"passwordExample"
}
I have also been given a PHP class that is supposed to manage these calls. This is the login function:
public function login ()
{
// Set up the parameters for a login attempt
$jsonData = array(
'login' => $this->loginUser,
'pword' => $this->loginPass,
);
// Make a login request
$jsonResponse = $this->pullResource
('/epf/login', 'POST', $jsonData);
return $jsonResponse;
}
So I have a few questions regarding this:
The document they sent says
"To make the request calls, a JSON object will need to be created and passed as a POST form parameter obj={jsonObject} for security reasons using content-type “application/x-www-form-urlencoded”."
I know that the login function contains the correct input values that USPS' REST API is wanting, but I'm not sure how to pass them as "obj", or how to apply the "content-type".
I have a "constant" defined at the top of my PHP script that looks like this:
const EPF_BASE_URL = 'https://epfws.usps.gov/ws/resources';
And I noticed in the actual functions that this part of the link is left out and they simply reference '/epf/login' as you can see above. Since "$this" contains lots of different values I'm wondering how it supposedly finds EPF_BASE_URL as needed. Is it similar to how 'using' directives work in C#?
What is the easiest way to call this function and display the result? This is my biggest question. Would I use a separate PHP class with an HTML form? I understand the concept of what it should do but I'm completely lost setting up a development environment for it.
I've been trying all of this with MAMP but would love to know if I'm on the right track or not.
That really depends on their API. Hopefully you get a string back that can be decoded to a JSON object (http://au.php.net/manual/en/function.json-decode.php). Some API might give a simple string that says 'SUCCESS' or 'FAIL'. You've got the code, so take a look at what $this->pullResponse() gives you.
If you've been given a PHP class that is supposed to support the API (hopefully from USPS), then it should already take care of putting the data in the form content, and ensuring is it submitted with the appropriate content-type.
A PHP const is more like a C# static string. It is very likely that the library will use the constant to create the end URL (i.e. EPF_BASE_URL . $resource). If you needed to run against a sand box environment, you could change that constant without having to change all the other code.
That's a very big question, because it depends on how you are programming your application. Procedural, MVC, existing frameworks, etc.
At the very least, you would set the loginUser and loginPass on the instantiated object, and call the login method`. You could then inspect the results, assuming the result is a JSON object, or use your favourite debugging method to see the contents.
I'm having a guess as the USPS API class name.
$uspsApi = new UspsApi();
$uspsApi->loginUser = 'username';
$uspsApi->loginPass = 'password';
$result = $uspsApi->login();
echo print_r($result, true);
I am using a php mysql based crm software which is made using Codeigniter.
I don't have any knowledge about Codeigniter.
I just customized it as per my requirements.
Whenever I am trying to save any data I am getting this error.
While using in Xampp I did not get these errors.
When I put it online I started to get these. Also I tried to ignore PHP errors, warnings using
error_reporting(0);
in my controller/admin.php
This would just hide the errors and not ignore them and proceed to the redirected page after the save.
If anything else is needed please let me know.
Undefined index -- that's the error you need to resolve here. You're most likely trying to access a property of $_GET or $_POST using an incorrect key name.
For the sake of debugging, try this:
if(isset($_GET['keyname'])) {
$myObj->prop = $_GET['keyname'];
} else {
show_error('No value set for keyname', 500);
}
I'm making a lot of assumptions about your code here, replace keyname with whatever you are trying to access.
For reference, you should probably switch to using the CodeIgniter Input Class to get values from GET/POST.
I'm from ASP.NET MVC background and this is first time I'm trying to write something in PHP.
In ASP.NET MVC we can develop models for our data and using the actions that we write we can get them or send them to another action. What I mean is that
public ActionResult Login_Action(LoginModel _Model) {
// Authenticating the user
return RedirectToAction(X);
}
when calling this the url that is shown in the address bar (in case of using GET, if it is POST nothing will be shown after the page name) will be:
www.WebsiteX.com/Login?Username=something&Password=something
The problem is that I don't even know how search for this in google (like by typing what exactly) because in Microsoft side, these are handled automatically the way I described.
But in case of PHP, how can I get the values in the address bar? do I have to get the actual address and then break the values down into arrays?
I'd appreciate any help.
First of all, this seems to be invalid for me: www.WebsiteX.com/Login?Username=something?Password=something The first parameter need to be ? and the others should be &.
Second: You can get your values of your parameters by accessing the $_GET global array.
Eg. for the username echo $_GET["Username"];
Are you using any framework? You should. And then, the Framework will give you the way to do that. In ASP.NET you use a Framework so do the same in PHP.
With vanille PHP you can get the GET values with $_GET['Username']. But please, use a framework.
I think that the most popular are Laravel and Symfony right now.
Example:
In laravel you can bind a parameter to a variable so you can do something like:
//Url: mywebsite.com/user/1/
Route::get('user/{id}', function($id)
{
return 'User '.$id;
});
Which is similar with the ASP.NET example.
I've tried to understand OOP for a while now (although haven't had much spare time to do much). While the cars and books analogies helped me understand the concept, I have kept failing trying to find a real world scenario (relating to a PHP program with database access).
Here is my most recent attempt at using OOP. It is a simple program submitting a user message to a database.
require_once('init.php');
require_once('Classes.php');
$message = new ContactMessage($db);
if(!$message->validateForm()){
$message -> returnSessionError('Failed to validate your form. Please try again');
header('Location: ../index.php?p=contact');
}else if($message->checkSubmissions(3,10) == false){ //form info okay, check if ip has submitted more than the allowed times. Sets max for 5mins and 24hrs respectively.
if($message->max5mins == true){ //maximum allowed messages in 5min period
$message ->returnSessionError('Too many messages have been sent from the same IP address.
Please wait at least 5 minutes and try again.');
header('Location: ../index.php?p=contact');
}elseif($message->max24hrs == true) { //max allowed in a day
$message ->returnSessionError('To prevent spam, your IP address has been blocked for 24 hours. Please try again later.');
header('Location: ../index.php?p=contact');
}
}else{ //everything is fine, add to database.
if($message -> insertToDB()){
$message -> returnSuccess('Thank you for your message, I\'ll get back to you ASAP.');
header('Location: ../index.php?p=contact');
}else{
$message -> returnSessionError('Something has gone wrong in our server - Please try again later.');
header('Location: ../index.php?p=contact');
}
}
To me, I'm still seeing my code as using a bunch of functions, except now it's wrapped around a Class. Is this the correct use of OOP, or am I just pretending to use it?
Thanks
In terms of OOP, you're doing it wrong because you're mixing concepts and responsibilities.
What you're doing here is dealing with data validation, including both input's and record's
The form validator basically consists of two parts:
Input validator
It basically checks if values are not empty, their maximal or minimal length.
Record Validator
It basically queries a storage to find out about record existence and generates appropriate error message.
Form Validator itself
Its a bridge between input and record validators. It basically check if fields are valid, then starts checking for records. If both inputs and records are valid, then its isValid() method returns true, otherwise it returns false and populates an array with error messages.
$dataMapper = new ContactMapper($pdo);
$inputValidator = new InputValidator();
$recordValidator = new RecordValidator($dataMapper);
$formValidator = new FormValidator($inputValidator, $recordValidator);
if ($formValidator->isValid($data)) {
if ($dataMapper->insert($data)){
// Success, do something like a redirect
} else {
// Failed to insert
}
} else {
print_r($formValidator->getErrors());
}
What would you gain here?
In terms of OOP, you're adhering to the Single-Responsibility Principle and Separation of Concerns at the same time, because you do encapsulate separated responsibility within a class that serves it. Thus you'll be able to modify one part of an application without altering another one.
Dealing with storage logic - is another responsibility too
And that should be basically encapsulated within a Mapper that abstract an access to a table.
Assumptions
I suppose this file of yours is, alone, just responsible for the execution of this script. No others scripts, neither HTML codes. Let's call it "post.php".
Answering the title question
In the OOP paradigm, you ALWAYS create your code oriented, not just when you can reuse code.
Answering the body question
In my opinion, in order for you to have a good OOP implementation, all scripts must be inside classes, except those that call the methods, and whatever else you need and can't put inside the classes (sorry, it's difficult to be more specific in the latter). You have two possibilities:
GET pages: get infos from the server and mix with the views (i.e. HTMLs; main methods in others languages), creating dinamic pages;
POST pages: targets from yours forms; in separated pages without any HTML, post infos to the server, like yours "post.php".
So, your script should be inside some class, it could be the ContactMessage, and in the "post.php", you just call the method of ContactMessage, something like postMessage, that does all this stuff.
Being more clear, i would create a postMessage method inside the ContactMessage class and call validateForm, checkSubmissions, insertToDB... from other classes (instead of the own ContactMessage), to create the "Single Responsibility" like the others said. One class responsible for the validation, one to abstract the DB and so on...
Final considerations
In my short experience, a real scenario it's a bit more complex than this, but you go adapting along the way corresponding to the needs.
One last thing: i would put all the redirections outside the class, in the "post.php", and would be just two possible redirections, one if fails and one if succeeds.
I am actually trying to monitor a PHP variable (may be as a separate thread but not possible in PHP) and fire a PHP function whenever the value of the variable changes.
eg: lets take a variable $_GLOBALS['foo']=1;
if at any point in the code, the value of $_GLOBALS['foo'] changes to something else, i want to fire a PHP function immediately.
The variable can be anywhere inside a loop or in a function,etc.
Why i want this: I have a variable which stores the last error occured as a text. If the value of the variable changes from "" to something else, i want to trigger an error. My LOGIC may seem a bit strange but this is what i would like to do.
Thanx in advance.
Edit: I tried: How to use monitors in PHP? and How can one use multi threading in PHP applications but does not seem to solve the problem.
The Code (Thought this could solve some of your doubts on my question):
public function addtag($tagarray,$uid,$tagtype="1")
{
$dbobj=new dboperations();
$uiobj=new uifriend();
$tagid=$uiobj->randomstring(30,DB_SOCIAL,SOCIAL_TAG,tag_tagid);
$c=0;
foreach($tagarray as $tags)
{
$c++;
$tagname=$tags["tagname"];
$taguid=$tags["tagid"];
$dbobj->dbinsert("INSERT INTO ".SOCIAL_TAG." (".tag_tagid.",".tag_fuid.",".tag_tuid.",".tag_tagname.",".tag_tagtype.") VALUES
('$tagid','$uid','$taguid','$tagname','$tagtype')",DB_SOCIAL);
}
if($c==0)
{
$lasterror="No tags were added";return "";
}
else
{
return $tagid;
}
}
Here, if i call a error handling function instead of monitoring the variable, it wont be advisable in my case since the error handling function may do any operation like give alert and redirect to a page or any similar operation.
I asked this question cause, i thought what if the script does not reach the line
return "";
It would affect the project's workflow. Thats what i am worried about.
And the variable i was talking about is $lasterror and i have many functions like this where $lasterror is used.
I saw this, so I built this:
https://github.com/leedavis81/vent
Should solve your problem.
There is no built-in way to do this in PHP, and there's no easy way to add it. It doesn't really feel right for the way the language works anyway.
Instead of setting a variable, you could build a custom function that handles the error - or use PHP's built-in error handling functionality using a custom error handler.
Another error handling method which comes close to what you want to do (I think) is exceptions.