I want to find all functions in a file - thats no problem:
preg_match_all("/function[\s\n]+(\S+)[\s\n]*\(/", $data, $outputData);
The problem is that if there are Javascript functions, they will get in the scheme, too.
Is it even possible to get only PHP-functions.
One indicator would be the <script>-Tag, but I have no Idea how to only track functions, which are not surounded by the script-Tag!
Thank you!
I had THE idea 2 seconds after writing the question.
$data = file_get_contents($file);
$data = preg_replace("/<script[^>]*>[\s\S]*?<\/script>/", "", $data);
preg_match_all("/function[\s\n]+(\S+)[\s\n]*\(/", $data, $outputData);
Just delete all the <script>-Tags!
If you would need them later, you also could save them (instead of replacing them) and add them later!
Just if someone else will have the same problem!
One option would be to remove all <script>...</script> tags before processing, but this assumes that you will only have JavaScript in these tags directly in the file. If you have a function or a library that generates HTML for you, it is possible for you to output JavaScript code without explicitly having the <script>...</script> tags in your PHP document. The issue is that you are using pattern matching, which can lead to an array of false positives.
To remove these false positives all together, you could use the PHP ReflectionFunction class to determine which functions are defined in PHP and which are not. Once you have an array of possible function names, use the following:
$data = file_get_contents($file);
$outputData;
$validMatches=array();
preg_match_all("/function[\s\n]+(\S+)[\s\n]*\(/", $data, $outputData);
foreach($outputData[1] as $match) {
$isValid=true;
try {
$reflection = new \ReflectionFunction($match);
} catch (\ReflectionException $e) {
$isValid=false;
}
if($isValid == true) {
$validMatches[]=$match;
}
}
This is more verbose but it will guarantee that you will get a list of only PHP function names.
Related
I have several HTML files on my server that contain JSON-LD script elements. I'm looking for an easy way to update specific elements without physically going into each file, changing the code, and re-saving it.
Specifically, I would like to programmatically loop through each file, find the datePosted property and update its value to the current date, then save the file on my server.
I'm mostly comfortable using PHP and I've done something like this with HTML files, but never tried updating JSON-LD before.
Wondering if anyone knows how to do this with JavaScript or PHP. If not could someone point me in the right direction of a good parser that works with JSON-LD?
Sample JSON-LD:
{
"#context": "http://schema.org",
"#type": "JobPosting",
"datePosted": "2018-01-23"
}
This was pretty easy, just needed to use json_decode and json_encode to make it work:
$file = "file-path-to-json-ld";
$string = file_get_contents($file); // pulls the file
$json = json_decode($string, true); //creates a searchable array
var_dump($json); // just to see what elements and values are in the decoded array
$json['element-name-in-json-ld'] = "new-value-for-element"; //change any value you like
$updatedString = json_encode($json, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); //re-encode backing into json
file_put_contents($file, $updatedString); // put file back
I have an array in jQuery that I am trying to convert to a PHP array by using Post:
$.post("http://www.samepage.com", {final_slip: JSON.stringify(final_slip)});
When I pass this dynamically created array "final_slip" into it :
[final_bet_game { final_user_id="1", final_game_id="1", final_game_type="spread_2",final_price="10", final_odds="1.8"}, final_bet_game { final_user_id="2", final_game_id="3", final_game_type="spread_2",final_price="1", final_odds="2.8"}, final_bet_game { final_user_id="3", final_game_id="14", final_game_type="spread_32",final_price="140", final_odds="1.8"}, final_bet_game { final_user_id="4", final_game_id="1", final_game_type="spread_2",final_price="10", final_odds="2.8"}, ]
I get this php outputted :
$data = $_POST['final_slip'];
print_r ( $data);
[{\"final_user_id\":\"1\",\"final_game_id\":\"1\",\"final_game_type\":\"spread_2\",\"final_price\":\"211\",\"final_odds\":\"1.8\"},{\"final_user_id\":\"1\",\"final_game_id\":\"2\",\"final_game_type\":\"spread_2\",\"final_price\":\"212\",\"final_odds\":\"1.8\"},{\"final_user_id\":\"1\",\"final_game_id\":\"parlay\",\"final_game_type\":\"\",\"final_price\":\"021\",\"final_odds\":\"\"}]
I tried to use the json_decod, but Im not getting any results. How can I get this to a usable php array? Would I be better off using ajax?
$.post("http://www.samepage.com", {myJsonString: JSON.stringify(myJsonString)});
But when I then try to access it in PHP I am not seeing any results.
And that tells you that you have another problem - PHP is not reporting errors. You want to turn error_reporting on.
In this case the likely cause is that your data is arriving into the $_POST array, and $myJsonString is not defined (automatic definition of parameters has been deprecated since PHP 5.3.0, and no longer available since PHP 5.4.0).
You should either do
if (array_key_exists('myJsonString', $_POST)) {
$myJsonString = $_POST['myJsonString'];
} else {
die("myJsonString not in _POST");
}
or try straight
$result = json_decode($_POST['myJsonString'], true);
The problem was the backslashes in the outout needed to be stripped out:
$result = $_POST['json_string'];
$test = urldecode(str_replace("\\","",$result));
$test2 = (json_decode($test,true));
print_r($test2);
I have a page that asks for a country code in a ComboBox, and I want it to load some other ComboBox with certain values that depend on the first one.
The secondary data should be loaded using a function inside a PHP class, whose instance I need to capture. I'm still not very familiar with AJAX and jQuery, so that's my problem.
My code is like this (I omitted the most obvious parts, of course):
new.html
<script src="findIDTypes.js"></script>
<form>
<select id="country_id" onchange="findIDTypes(this.id)">
<option value="AR">Argentina</option>
<option value="BR">Brazil</option>
</select>
</form>
dbfunctions.php
class DBConn {
public function GetInstance($host = FALSE, $user = FALSE, $pass = FALSE) {
static $_instance = FALSE;
if ($_instance === FALSE) {
if ($host == FALSE || $user == FALSE || $pass == FALSE) {
// Error! Can't instantiate
}
$_instance = new DBConn($host, $user, $pass);
}
// OK!
return $_instance;
}
public function findIDTypes($country_id) {
// Returns array of value pairs (Code, Description)
}
}
findIDTypes.js
function findIDTypes(value_to_search) {
// ???
}
What I need my AJAX/jQuery (not sure which) function to do is:
Capture the instance of DBConn
Call the instance function "findIDTypes()" in the PHP class
Retrieve the array of (C,D) pairs and load them, one by one, on the secondary combobox
What exactly do I need to do to complete steps 1 and 2, if it's possible at all?
Thanks! :)
php and javascript are entirely different, and while you can use php to generate javascript code before the page is rendered, you cannot call php functions from javascript.
This is because php runs on the server, and javascript (which the exception of Node.js!) runs in the browser.
To solve this, you need to expose your php as an API using HTTP GET or POST methods.
Steps
Build your php page to accept $_GET url query parameters or $_POST parameters, in one form or another.
Decide upon a method of communicating your data on the server end back to your browser's javascript/ajax. For this, I highly recommend json for an innumerable number of reasons. It easily integrates with php via json_encode() and json_decode(), and javascript via JSON.parse() and JSON.stringify().
Once you've established your "API" as it were in php, you can easily use jQuery's $.ajax to send and retrieve data to your php. Since your example is relatively simple, it may be as easy as something like http://yoursite.com/?init=DBConn_GetInstance and handling the $_GET['init'] function, then outputting the results of your function.
how do we check if table is empty with cakephp and ajax? In my index.ctp I have an image that when clicked, it will inform the user if the table is empty or not. If it's empty, an alert box will appear, and if it's not, it will be redirected to another page.
<?php
echo $this->Html->image('movie.png', array('onclick'=>'check()'));
?>
JAVASCRIPT:
function check(){
//check browser comp, create an object
object.GET("GET", url, false);
//rest of the code here
}
MoviesController.php
function index(){
//something here
$moviecount=$this->Movies->find('count');
$this->set('moviecount', $moviecount);
}
I know how to do it using the normal PHP coding, but with cakephp, and since I am new, I dont know yet. For regular PHP coding, I used the GET method for AJAX, and I can specify the URL for the PHP query inside the GET function. I don't know how to do it using cake.
You need to set the layout to AJAX then render your view. I strongly recommend not to use the index() method for this. Instead you can define a whatever() method in the MoviesController:
function whatever(){
//It is not a bad idea to do this only for GET - use the RequestHandlerComponent
$this->layout = 'ajax';
$moviecount=$this->Movies->find('count');
$this->set('moviecount', $moviecount);
}
The in the view file whatever.ctp:
echo json_encode(array('moviecount' = $moviecount));
//It is a good idea to add an isset() ternary check here like:
// echo isset($moviecount) ? json_encode(array('moviecount' => $moviecount)) : json_encode(false);
Notice that I am creating an array and encoding it to JSON. This is the way to convert variables to and from JSON. To decode use json_decode() of course.
The Client-side code really depends on what you're using to make the AJAX call but let us say that the call succeeded and you got the data back in the data variable:
//Make the AJAX call to example.com/movies/whatever via GET
//Check what data is but it should definitely be an array
if (data['moviecount']) {
//If moviecount is 0 it will go in the else statement - 0 i falsey
window.location = 'example.com/redirect/url';
} else {
alert('No records');
}
I advice against using alert() to inform the user that there are no records. Better put it somewhere in the page - in some div or whatever. Since this is an AJAX request it could be repeated many times. Consecutive use of alert() is not really user-friendly in this case.
As I'm developing my WebIDE, I keep coming up with questions that I cannot answer myself. This is because the project is supposed to help others create what they would "normally" create, but faster (i.e. as automated as possible). In this light, my question is how to you implement a PHP backend?
Here is what I do. I like to create "functions" that the client JavaScript can call. Usually, I send (via POST and JSON) a variable called "action" which holds the name of the "function" I am calling (as well as any arguments I wish to send it). The PHP code, then, looks something like this:
if(issset($_POST['action'])) {
//function foo(arg1,arg2)
if($_POST['action'] == 'foo') {
$arg1 = $_POST['arg1'];
$arg2 = $_POST['arg2'];
//do stuff
}
}
I can still reference other real functions I create in PHP, but I find that this is a nice way to organize everything and easy to implement in both JavaScript and PHP.
What do you do?
Edit 1: Ok, based on the first two answers to this question, I do not think I am explaining myself well.
I am asking how do you create a PHP back end. The idea is that you have your AJAX client written in JavaScript (or maybe something else, it doesn't matter), and then it will call your backend PHP with POST or GET data. Based on this data, your backend will do what it needs to do (maybe it will simply update the database, and maybe even return information, again: it doesn't matter).
The question now is: how do you tell it what to do? What do you send via POST/GET and how do you interpret it in your backend?
I send all data to the backend in a big GET array.
actionpage.php?action=post¶meters[parameter1]=value1¶meters[parameter2]=value2
If you print_r($_GET), on the PHP side you'll see:
array(
"action" => "create",
"parameters" => array("parameter1"=>"value1","parameter2"=>"value2")
)
What this does is allow you to loop through your parameters. You can say in the pap
if($_GET['action'] == 'create'){
foreach($_GET['parameters'] as $key=>$value){ //something
The question now is: how do you tell
it what to do? What do you send via
POST/GET and how do you interpret it
in your backend?
Choose your own conventions. For example use an "action" value in your JSON data that tells the action, then add more parameters. You can spy on various websites's Ajax messages with Firebug extension in Firefox if you want to see what other websites do.
For example the Json POST data could be:
{
action: "create",
fields: {
firstname: "John",
lastname: "Doe",
age: 32
}
}
To which you could reply with the ID of the newly created record.
To delete the record:
{
action: "delete",
keys: {
id: 4654564
}
}
etc.
In the php ajax handler you could have something as simple as a switch:
$jsonData = Services_Json::decode($_POST['json']);
switch ($jsonData->action)
{
case "save":
if (validate_json_data($jsonData->fields))
{
UsersPeer::create($jsonData->fields);
}
break;
case "delete":
/* etc */
}
// return a json reply with
$jsonReply = new stdClass;
$jsonReply->status = "ok";
$jsonReply->statusMessage = "Record succesfully created";
echo Services_Json::encode($jsonReply);
exit;
Javascript, say prototype Ajax.Request responder function will output the error message in a specially created DIV if "status" is not "ok", etc...
I use a front page controller which handles my routing. If you set up mod-rewrite you can have very clean endpoints where the first segment of your url refers to the controller (class) and then the subsequent segments would refer to the methods inside followed by the parameters being passed to the method.
http://domain.com/class/method/param1/param2
this website will answer all your ajax questions. I found it really helpful.
http://ajaxpatterns.org/XMLHttpRequest_Call
You need to organize functions? It's called 'class'.
/// todo: add error processing
$name=$_GET['action'];
$args=json_decode($_GET['args']); /// or just subarray, doesn't matter
/// 'Action' is constant here but in reality you will need more then one class for this
/// because you will want modules in your framework
if(method_exists('Action',$name))
call_user_func_array(array('Action',$name),$args);
else { /* incorrect parameters processing */ }
/// Ajax-available functions are here
class Action
{
public static function action1()
{
echo 'action1';
}
public static function action2()
{
echo 'action2';
}
}
I do something very similar. What you need is a JSON object to pass back to the javascript. When you are done with your PHP, you can call json_encode to pass an object back to the front end. From there you can do more with it in Javascript or format it however you want.
There is more information on a similar question here:
Best way to transfer an array between PHP and Javascript
Edit: After reading your edit, I think what you are doing is fine. When you send the AJAX request from Javascript include a variable like "action", or whatever youd like. From there you can check what the action is via a case and switch statement.
I usually write the php functions as normal functions.
fn1(arg1, arg2){
//do stuff here
}
fn2(arg3){
//do stuff here
}
I pass the name of the function in a variable called action. Then do this:
foreach($_POST as $key => $value)
$$key = $value;
To assign create variables of the same name as the arguments.
Then use a switch-case to call the appropriate function like so:
switch($action){
case 'fn1':fn1(arg1,arg2);
break;
case 'fn2':fn2(arg3);
break;
}
Is this what you are looking for?
Edit: You could use the PHP SOAP and XML-RPC extension to develop a webservice, where if you specify the function name in the SOAP request, that function will be automatically executed (you don't have to write the switch-case or if). I've used it in Java, but am not sure how exactly it works in PHP.